() : rightRoot.children;
diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/SnapshotRecursiveSummary.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/SnapshotRecursiveSummary.java
new file mode 100644
index 00000000000..d34bc38c4b6
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/SnapshotRecursiveSummary.java
@@ -0,0 +1,121 @@
+/*
+ * 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.zookeeper.server;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Set;
+import java.util.TreeSet;
+import org.apache.yetus.audience.InterfaceAudience;
+import org.apache.zookeeper.ZKUtil;
+import org.apache.zookeeper.common.PathUtils;
+import org.apache.zookeeper.util.ServiceUtils;
+
+/**
+ * Recursively summarizes snapshot subtree data sizes and descendant counts.
+ * Only non-leaf nodes are printed, but totals include all descendants and ephemeral nodes.
+ * The maximum depth limits output, not traversal; zero means unlimited output depth.
+ *
+ * Backported from Apache ZooKeeper commit 05b215994f5e145c2758c4089828b57ba471b329
+ * (ZOOKEEPER-4566).
+ */
+@InterfaceAudience.Public
+public class SnapshotRecursiveSummary {
+
+ public static void main(String[] args) {
+ if (args.length != 3) {
+ System.err.println(getUsage());
+ ServiceUtils.requestSystemExit(ExitCode.INVALID_INVOCATION.getValue());
+ return;
+ }
+ try {
+ new SnapshotRecursiveSummary().run(args[0], args[1], Integer.parseInt(args[2]));
+ } catch (IllegalArgumentException e) {
+ System.err.println(e.getMessage());
+ System.err.println(getUsage());
+ ServiceUtils.requestSystemExit(ExitCode.INVALID_INVOCATION.getValue());
+ } catch (IOException e) {
+ System.err.println("Unable to read snapshot: " + e.getMessage());
+ ServiceUtils.requestSystemExit(ExitCode.UNEXPECTED_ERROR.getValue());
+ }
+ }
+
+ public void run(String snapshotFileName, String startingNode, int maxDepth) throws IOException {
+ PathUtils.validatePath(startingNode);
+ if (maxDepth < 0) {
+ throw new IllegalArgumentException("max_depth must be a non-negative integer.");
+ }
+ String error = ZKUtil.validateFileInput(snapshotFileName);
+ if (error != null) {
+ throw new IllegalArgumentException(error);
+ }
+ DataTree dataTree = SnapshotComparer.getSnapshot(new File(snapshotFileName));
+ if (dataTree.getNode(startingNode) == null) {
+ throw new IllegalArgumentException("Starting node does not exist: " + startingNode);
+ }
+ StringBuilder builder = new StringBuilder();
+ printZnode(dataTree, startingNode, builder, 0, maxDepth);
+ System.out.println(builder);
+ }
+
+ private long[] printZnode(DataTree dataTree, String name, StringBuilder builder, int level, int maxDepth) {
+ DataNode node = dataTree.getNode(name);
+ Set children;
+ long dataSize;
+ synchronized (node) {
+ dataSize = node.data == null ? 0 : node.data.length;
+ children = new TreeSet<>(node.getChildren());
+ }
+ long[] result = {1L, dataSize};
+ if (children.isEmpty()) {
+ return result;
+ }
+ StringBuilder childBuilder = new StringBuilder();
+ for (String child : children) {
+ long[] childResult = printZnode(dataTree, name + (name.equals("/") ? "" : "/") + child,
+ childBuilder, level + 1, maxDepth);
+ result[0] += childResult[0];
+ result[1] += childResult[1];
+ }
+ if (maxDepth == 0 || level <= maxDepth) {
+ String indent = String.join("", Collections.nCopies(level, "--"));
+ builder.append(indent).append(" ").append(name).append("\n");
+ builder.append(indent).append(" children: ").append(result[0] - 1).append("\n");
+ builder.append(indent).append(" data: ").append(result[1]).append("\n");
+ builder.append(childBuilder);
+ }
+ return result;
+ }
+
+ public static String getUsage() {
+ String newLine = System.lineSeparator();
+ return String.join(newLine,
+ "USAGE:",
+ "",
+ "SnapshotRecursiveSummary ",
+ "",
+ "snapshot_file: path to the zookeeper snapshot",
+ "starting_node: the absolute path in the zookeeper tree where traversal should begin",
+ "max_depth: non-negative output depth. 0 displays every non-leaf node; "
+ + "1 displays the starting node and its non-leaf children; 2 adds another level, and so on. "
+ + "This ONLY affects the level of details displayed, NOT the calculation.");
+ }
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotComparerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotComparerTest.java
new file mode 100644
index 00000000000..c90653e1d4d
--- /dev/null
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotComparerTest.java
@@ -0,0 +1,466 @@
+/*
+ * 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.zookeeper.server;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.io.FileUtils;
+import org.apache.jute.BinaryInputArchive;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.server.persistence.FileSnap;
+import org.apache.zookeeper.server.persistence.SnapStream;
+import org.apache.zookeeper.server.persistence.SnapStream.StreamMode;
+import org.apache.zookeeper.test.ClientBase;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+public class SnapshotComparerTest extends ZKTestCase {
+
+ private SnapshotToolTestSupport support;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ support = new SnapshotToolTestSupport();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ support.close();
+ }
+
+ @Test
+ public void testAddedAndDeletedSubtrees() throws Exception {
+ DataTree left = new DataTree();
+ support.addNode(left, "/app", new byte[1]);
+ support.addNode(left, "/app/removed", new byte[2]);
+ support.addNode(left, "/app/removed/leaf", new byte[3]);
+ DataTree right = new DataTree();
+ support.addNode(right, "/app", new byte[1]);
+ support.addNode(right, "/app/added", new byte[4]);
+ support.addNode(right, "/app/added/a", new byte[5]);
+ support.addNode(right, "/app/added/b", null);
+
+ String output = compare(left, right, "0", "0", "-d");
+
+ assertThat(output, containsString("Node found in both trees. Delta: 4 bytes, 1 descendants"));
+ assertThat(output, containsString("Node /app found in both trees. Delta: 4 bytes, 1 descendants"));
+ assertThat(output, containsString("Node /app/removed found only in left tree. Descendant size: 5. Descendant count: 1"));
+ assertThat(output, containsString("Node /app/removed/leaf found only in left tree. Descendant size: 3. Descendant count: 0"));
+ assertThat(output, containsString("Node /app/added found only in right tree. Descendant size: 9. Descendant count: 2"));
+ assertThat(output, containsString("Node /app/added/a found only in right tree. Descendant size: 5. Descendant count: 0"));
+ assertThat(output, containsString("Filtered right node /app/added/b of size 0"));
+ assertTrue(output.indexOf("Node /app/added found") < output.indexOf("Node /app/removed found"), output);
+ assertThat(output, containsString("All layers compared."));
+ }
+
+ @Test
+ public void testSignedByteDeltasAndExclusiveThreshold() throws Exception {
+ DataTree left = new DataTree();
+ support.addNode(left, "/grow", new byte[1]);
+ support.addNode(left, "/shrink", new byte[5]);
+ DataTree right = new DataTree();
+ support.addNode(right, "/grow", new byte[5]);
+ support.addNode(right, "/shrink", new byte[1]);
+
+ String filtered = compare(left, right, "4", "0", "--debug");
+ String included = compare(left, right, "3", "2147483647");
+
+ assertThat(filtered, containsString("Filtered node /grow of left size 1, right size 5"));
+ assertThat(filtered, not(containsString("Node /grow found")));
+ assertThat(included, containsString("Node /grow found in both trees. Delta: 4 bytes, 0 descendants"));
+ assertThat(included, containsString("Node /shrink found in both trees. Delta: -4 bytes, 0 descendants"));
+ }
+
+ @Test
+ public void testDescendantThresholdWithNullData() throws Exception {
+ DataTree left = new DataTree();
+ support.addNode(left, "/app", null);
+ DataTree right = new DataTree();
+ support.addNode(right, "/app", null);
+ support.addNode(right, "/app/child", null);
+
+ String filtered = compare(left, right, "2147483647", "1", "-d");
+ String included = compare(left, right, "2147483647", "0");
+ String removed = compare(right, left, "2147483647", "0");
+
+ assertThat(filtered, containsString("Filtered node /app of left size 0, right size 0"));
+ assertThat(filtered, not(containsString("Node /app found")));
+ assertThat(included, containsString("Node /app found in both trees. Delta: 0 bytes, 1 descendants"));
+ assertThat(removed, containsString("Node /app found in both trees. Delta: 0 bytes, -1 descendants"));
+ }
+
+ @Test
+ public void testEphemeralNodesAreIncluded() throws Exception {
+ DataTree right = new DataTree();
+ right.createNode("/ephemeral", new byte[7], ZooDefs.Ids.OPEN_ACL_UNSAFE, 0x123L, -1, 1, 1);
+
+ String output = compare(new DataTree(), right, "0", "0");
+
+ assertThat(output, containsString("Node /ephemeral found only in right tree. Descendant size: 7. Descendant count: 0"));
+ assertThat(output, containsString("Node found in both trees. Delta: 7 bytes, 1 descendants"));
+ }
+
+ @Test
+ public void testEqualLengthPayloadsAreOnlySizeCompared() throws Exception {
+ DataTree left = new DataTree();
+ support.addNode(left, "/equal", "aa".getBytes(StandardCharsets.UTF_8));
+ DataTree right = new DataTree();
+ support.addNode(right, "/equal", "bb".getBytes(StandardCharsets.UTF_8));
+
+ String output = compare(left, right, "0", "0", "-d");
+
+ assertThat(output, containsString("Filtered node /equal of left size 2, right size 2"));
+ assertThat(output, not(containsString("Node /equal found")));
+ assertThat(output, containsString("All layers compared."));
+ }
+
+ @ParameterizedTest
+ @EnumSource(StreamMode.class)
+ public void testMixedCompressionAndReadOnlyLoader(StreamMode mode) throws Exception {
+ DataTree rightTree = new DataTree();
+ support.addNode(rightTree, "/node", new byte[3]);
+ File left = support.snapshot(new DataTree(), StreamMode.CHECKED, true);
+ for (boolean digest : new boolean[]{false, true}) {
+ File right = support.snapshot(rightTree, mode, digest);
+ File range = new File(right.getParentFile(), "snapshot.1-2" + mode.getFileExtension());
+ Files.move(right.toPath(), range.toPath());
+ byte[] before = Files.readAllBytes(range.toPath());
+ try {
+ String output = run("", arguments(left, range, "0", "0")).success();
+ assertThat(output, containsString("Node /node found only in right tree. Descendant size: 3. Descendant count: 0"));
+ assertArrayEquals(new byte[3], SnapshotComparer.getSnapshot(range).getNode("/node").data);
+ assertArrayEquals(before, Files.readAllBytes(range.toPath()));
+ } finally {
+ Files.delete(range.toPath());
+ }
+ }
+ }
+
+ @Test
+ public void testCheckedInSnapshotFixtures() throws Exception {
+ String output = run("", arguments(support.fixture("snapshot.0"), support.fixture("snapshot.2"), "0", "0")).success();
+
+ assertThat(output, containsString("Node /test_node found only in right tree. Descendant size: 5000. Descendant count: 0"));
+ assertThat(output, containsString("Node found in both trees. Delta: 5000 bytes, 1 descendants"));
+ }
+
+ @Test
+ public void testInteractivePathsAndDepths() throws Exception {
+ DataTree leftTree = new DataTree();
+ support.addNode(leftTree, "/app", null);
+ support.addNode(leftTree, "/app/leaf", new byte[1]);
+ DataTree rightTree = new DataTree();
+ support.addNode(rightTree, "/app", null);
+ support.addNode(rightTree, "/app/leaf", new byte[3]);
+ File left = support.snapshot(leftTree, StreamMode.CHECKED, true);
+ File right = support.snapshot(rightTree, StreamMode.CHECKED, true);
+
+ String output = run("/\n/app\n/app/leaf\n/missing\n-1\n999\nbad\n1\n\n\n",
+ arguments(left, right, "0", "0", "--interactive")).success();
+
+ assertThat(output, containsString("Analysis for node /"));
+ assertThat(output, not(containsString("Path / is neither found")));
+ assertThat(output, containsString("Node /app found in both trees. Delta: 2 bytes, 0 descendants"));
+ assertThat(output, containsString("Node /app/leaf found in both trees. Delta: 2 bytes, 0 descendants"));
+ assertThat(output, not(containsString("Path /app/leaf is neither found")));
+ assertThat(output, containsString("Path /missing is neither found in left tree nor right tree."));
+ assertThat(output, containsString("Depth must be in range [0, 2]"));
+ assertThat(output, containsString("Input bad is not valid."));
+ assertThat(output, containsString("Analysis for depth 1"));
+ assertThat(output, containsString("All layers compared."));
+ }
+
+ @Test
+ public void testEmptySnapshotAndInteractiveEndOfInput() throws Exception {
+ File snapshot = support.snapshot(new DataTree(), StreamMode.CHECKED, false);
+ String batch = run("", arguments(snapshot, snapshot, "0", "0")).success();
+ String interactive = run("", arguments(snapshot, snapshot, "0", "0", "-i")).success();
+
+ assertThat(batch, containsString("Node count: 4"));
+ assertThat(batch, containsString("Total size: 0"));
+ assertThat(batch, containsString("All layers compared."));
+ assertThat(batch, not(containsString("Delta:")));
+ assertThat(interactive, containsString("End of input."));
+ assertThat(interactive, not(containsString("All layers compared.")));
+ }
+
+ @Test
+ public void testDeepTreeDepthsAndTotals() throws Exception {
+ DataTree right = new DataTree();
+ String path = "";
+ for (int i = 0; i < 64; i++) {
+ path += "/n";
+ support.addNode(right, path, new byte[1]);
+ }
+
+ String output = compare(new DataTree(), right, "0", "0");
+
+ assertThat(output, containsString("Max depth: 65"));
+ assertThat(output, containsString("Node found in both trees. Delta: 64 bytes, 64 descendants"));
+ assertThat(output, containsString("Node /n found only in right tree. Descendant size: 64. Descendant count: 63"));
+ assertThat(output, containsString("Analysis for depth 64"));
+ assertThat(output, containsString("Node " + path + " found only in right tree. Descendant size: 1. Descendant count: 0"));
+ assertThat(output, containsString("All layers compared."));
+ }
+
+ @Test
+ public void testInvalidArgumentsAndFiles() throws Exception {
+ File snapshot = support.snapshot(new DataTree(), StreamMode.CHECKED, true);
+ run("").invalidInvocation();
+ run("", "-l", snapshot.toString()).invalidInvocation();
+ for (String invalid : Arrays.asList("-1", "NaN", "2147483648")) {
+ run("", arguments(snapshot, snapshot, invalid, "0")).invalidInvocation();
+ run("", arguments(snapshot, snapshot, "0", invalid)).invalidInvocation();
+ }
+ run("", arguments(snapshot, snapshot, "0", "0", "--unknown")).invalidInvocation();
+ run("", arguments(snapshot, snapshot, "0", "0", "extra")).invalidInvocation();
+ for (File invalid : Arrays.asList(new File(support.directory, "missing"), support.directory)) {
+ run("", arguments(invalid, snapshot, "0", "0")).invalidInvocation();
+ run("", arguments(snapshot, invalid, "0", "0")).invalidInvocation();
+ }
+ }
+
+ @Test
+ public void testCorruptSnapshots() throws Exception {
+ File valid = support.snapshot(new DataTree(), StreamMode.CHECKED, true);
+ for (File corrupt : support.corruptSnapshots()) {
+ SnapshotToolTestSupport.Result result = run("", arguments(corrupt, valid, "0", "0"));
+ result.readFailure();
+ assertThat(result.output, not(containsString("All layers compared.")));
+ }
+ }
+
+ @Test
+ public void testShellLauncher() throws Exception {
+ assumeFalse(System.getProperty("os.name").startsWith("Windows"));
+ DataTree rightTree = new DataTree();
+ support.addNode(rightTree, "/node", new byte[3]);
+ File left = support.snapshot(new DataTree(), StreamMode.CHECKED, true);
+ File right = support.snapshot(rightTree, StreamMode.GZIP, true);
+ for (String flags : Arrays.asList("", "-Xms32m -Xmx128m")) {
+ String output = support.runLauncher("zkSnapshotComparer.sh", flags,
+ "-l", left.toString(), "-r", right.toString(), "-b", "0", "-n", "0").success();
+ assertThat(output, containsString("Node /node found only in right tree. Descendant size: 3. Descendant count: 0"));
+ }
+ support.runLauncher("zkSnapshotComparer.sh", "").invalidInvocation();
+ }
+
+ private String compare(DataTree left, DataTree right, String bytes, String nodes, String... flags) throws Exception {
+ return run("", arguments(support.snapshot(left, StreamMode.CHECKED, true),
+ support.snapshot(right, StreamMode.CHECKED, true),
+ bytes, nodes, flags)).success();
+ }
+
+ private String[] arguments(File left, File right, String bytes, String nodes, String... flags) {
+ List args = new ArrayList<>(Arrays.asList("--left", left.toString(), "--right", right.toString(),
+ "--bytes", bytes, "--nodes", nodes));
+ args.addAll(Arrays.asList(flags));
+ return args.toArray(new String[0]);
+ }
+
+ private SnapshotToolTestSupport.Result run(String input, String... args) throws Exception {
+ return support.run("org.apache.zookeeper.server.SnapshotComparer", input, args);
+ }
+
+ static class SnapshotToolTestSupport {
+
+ final File directory = ClientBase.createEmptyTestDir();
+ private int nextFile;
+
+ SnapshotToolTestSupport() throws IOException {
+ }
+
+ void addNode(DataTree tree, String path, byte[] data) throws Exception {
+ tree.createNode(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, 0, -1, 1, 1);
+ }
+
+ File fixture(String name) {
+ return new File(System.getProperty("test.data.dir", "src/test/resources/data"),
+ "buffersize/snapshot/version-2/" + name);
+ }
+
+ File snapshot(DataTree tree, StreamMode mode, boolean digest) throws IOException {
+ File snapshots = new File(directory, "snapshots with spaces");
+ assertTrue(snapshots.isDirectory() || snapshots.mkdir());
+ File file = new File(snapshots, "snapshot." + Integer.toHexString(++nextFile) + mode.getFileExtension());
+ StreamMode previousMode = SnapStream.getStreamMode();
+ boolean previousDigest = ZooKeeperServer.isDigestEnabled();
+ try {
+ SnapStream.setStreamMode(mode);
+ ZooKeeperServer.setDigestEnabled(digest);
+ new FileSnap(null).serialize(tree, Collections.singletonMap(0x123L, 30000), file, false);
+ } finally {
+ SnapStream.setStreamMode(previousMode);
+ ZooKeeperServer.setDigestEnabled(previousDigest);
+ }
+ return file;
+ }
+
+ List corruptSnapshots() throws IOException {
+ List files = new ArrayList<>();
+ File badHeader = snapshot(new DataTree(), StreamMode.CHECKED, true);
+ byte[] bytes = Files.readAllBytes(badHeader.toPath());
+ bytes[0] ^= 1;
+ Files.write(badHeader.toPath(), bytes);
+ files.add(badHeader);
+
+ File truncated = snapshot(new DataTree(), StreamMode.CHECKED, true);
+ bytes = Files.readAllBytes(truncated.toPath());
+ Files.write(truncated.toPath(), Arrays.copyOf(bytes, bytes.length / 2));
+ files.add(truncated);
+
+ File checksum = snapshot(new DataTree(), StreamMode.CHECKED, true);
+ bytes = Files.readAllBytes(checksum.toPath());
+ ByteArrayInputStream input = new ByteArrayInputStream(bytes);
+ new FileSnap(null).deserialize(new DataTree(), new HashMap(),
+ BinaryInputArchive.getArchive(input));
+ int sealOffset = bytes.length - input.available();
+ bytes[sealOffset] ^= 1;
+ Files.write(checksum.toPath(), bytes);
+ files.add(checksum);
+
+ File marker = snapshot(new DataTree(), StreamMode.CHECKED, false);
+ bytes = Files.readAllBytes(marker.toPath());
+ bytes[sealOffset + 12] = 'x';
+ Files.write(marker.toPath(), bytes);
+ files.add(marker);
+
+ File partialDigest = snapshot(new DataTree(), StreamMode.CHECKED, true);
+ bytes = Files.readAllBytes(partialDigest.toPath());
+ Files.write(partialDigest.toPath(), Arrays.copyOf(bytes, sealOffset + 14));
+ files.add(partialDigest);
+
+ File digestSeal = snapshot(new DataTree(), StreamMode.CHECKED, true);
+ bytes = Files.readAllBytes(digestSeal.toPath());
+ bytes[bytes.length - 13] ^= 1;
+ Files.write(digestSeal.toPath(), bytes);
+ files.add(digestSeal);
+
+ File trailing = snapshot(new DataTree(), StreamMode.CHECKED, true);
+ bytes = Files.readAllBytes(trailing.toPath());
+ Files.write(trailing.toPath(), Arrays.copyOf(bytes, bytes.length + 1));
+ files.add(trailing);
+
+ File gzipTrailer = snapshot(new DataTree(), StreamMode.GZIP, true);
+ bytes = Files.readAllBytes(gzipTrailer.toPath());
+ bytes[bytes.length - 1] ^= 1;
+ Files.write(gzipTrailer.toPath(), bytes);
+ files.add(gzipTrailer);
+ return files;
+ }
+
+ Result run(String mainClass, String input, String... args) throws Exception {
+ List command = new ArrayList<>(Arrays.asList(
+ new File(System.getProperty("java.home"), "bin/java").toString(),
+ "-Xmx128m",
+ "-Djava.io.tmpdir=" + directory.getCanonicalPath(),
+ "-cp",
+ System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")),
+ mainClass));
+ command.addAll(Arrays.asList(args));
+ return runProcess(new ProcessBuilder(command), input);
+ }
+
+ Result runLauncher(String launcher, String flags, String... args) throws Exception {
+ File script = new File(System.getProperty("basedir", "."), "../bin/" + launcher);
+ assertTrue(script.canExecute(), script.toString());
+ List command = new ArrayList<>(Collections.singletonList(script.getCanonicalPath()));
+ command.addAll(Arrays.asList(args));
+ ProcessBuilder builder = new ProcessBuilder(command);
+ builder.environment().put("JAVA_HOME", System.getProperty("java.home"));
+ builder.environment().put("CLASSPATH",
+ System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")));
+ builder.environment().put("JVMFLAGS", flags);
+ builder.environment().put("JAVA_TOOL_OPTIONS", "-Djava.io.tmpdir=\"" + directory.getCanonicalPath() + "\"");
+ return runProcess(builder, "");
+ }
+
+ private Result runProcess(ProcessBuilder builder, String input) throws Exception {
+ File outputFile = new File(directory, "output-" + ++nextFile);
+ File inputFile = new File(directory, "input-" + nextFile);
+ Files.write(inputFile.toPath(), input.getBytes(StandardCharsets.UTF_8));
+ Process process = builder
+ .redirectInput(inputFile)
+ .redirectErrorStream(true)
+ .redirectOutput(outputFile)
+ .start();
+ try {
+ assertTrue(process.waitFor(30, TimeUnit.SECONDS), "CLI did not exit: " + builder.command());
+ return new Result(process.exitValue(),
+ new String(Files.readAllBytes(outputFile.toPath()), StandardCharsets.UTF_8));
+ } finally {
+ if (process.isAlive()) {
+ process.destroyForcibly();
+ assertTrue(process.waitFor(10, TimeUnit.SECONDS), "CLI did not stop: " + builder.command());
+ }
+ }
+ }
+
+ void close() throws IOException {
+ FileUtils.deleteDirectory(directory);
+ }
+
+ static class Result {
+
+ final int exitCode;
+ final String output;
+
+ Result(int exitCode, String output) {
+ this.exitCode = exitCode;
+ this.output = output;
+ }
+
+ String success() {
+ assertEquals(ExitCode.EXECUTION_FINISHED.getValue(), exitCode, output);
+ return output;
+ }
+
+ void invalidInvocation() {
+ assertEquals(ExitCode.INVALID_INVOCATION.getValue(), exitCode, output);
+ assertThat(output.toLowerCase(), containsString("usage:"));
+ }
+
+ void readFailure() {
+ assertEquals(ExitCode.UNEXPECTED_ERROR.getValue(), exitCode, output);
+ assertThat(output, containsString("Unable to read snapshot"));
+ }
+ }
+ }
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotRecursiveSummaryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotRecursiveSummaryTest.java
new file mode 100644
index 00000000000..be006a15a2c
--- /dev/null
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotRecursiveSummaryTest.java
@@ -0,0 +1,244 @@
+/*
+ * 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.zookeeper.server;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.Arrays;
+import java.util.stream.Collectors;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.server.SnapshotComparerTest.SnapshotToolTestSupport;
+import org.apache.zookeeper.server.persistence.SnapStream.StreamMode;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+public class SnapshotRecursiveSummaryTest extends ZKTestCase {
+
+ private SnapshotToolTestSupport support;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ support = new SnapshotToolTestSupport();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ support.close();
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {0, 1, 2, Integer.MAX_VALUE})
+ public void testRecursiveSubtreeTotalsAndDepth(int depth) throws Exception {
+ String output = summarize(tree(), "/app", Integer.toString(depth));
+ String expected = " /app\n children: 5\n data: 17\n"
+ + "-- /app/branch\n-- children: 2\n-- data: 8";
+ if (depth != 1) {
+ expected += "\n---- /app/branch/deep\n---- children: 1\n---- data: 5";
+ }
+ assertEquals(expected, entries(output));
+ }
+
+ @Test
+ public void testRootIncludesItsOwnData() throws Exception {
+ DataTree tree = tree();
+ tree.setData("/", new byte[11], 1, 1, 1);
+
+ String output = summarize(tree, "/", "1");
+
+ assertEquals(" /\n children: 9\n data: 28\n"
+ + "-- /app\n-- children: 5\n-- data: 17\n"
+ + "-- /zookeeper\n-- children: 2\n-- data: 0", entries(output));
+ }
+
+ @Test
+ public void testSelectedLeafAndNullData() throws Exception {
+ assertEquals("", entries(summarize(tree(), "/app/leaf", "0")));
+ DataTree tree = new DataTree();
+ support.addNode(tree, "/app", null);
+ support.addNode(tree, "/app/leaf", null);
+
+ assertEquals(" /app\n children: 1\n data: 0", entries(summarize(tree, "/app", "0")));
+ }
+
+ @Test
+ public void testEmptySnapshot() throws Exception {
+ String output = summarize(new DataTree(), "/", "0");
+
+ assertEquals(" /\n children: 3\n data: 0\n"
+ + "-- /zookeeper\n-- children: 2\n-- data: 0", entries(output));
+ }
+
+ @Test
+ public void testDeepTreeTotalsBeyondOutputLimit() throws Exception {
+ DataTree tree = new DataTree();
+ support.addNode(tree, "/app", new byte[2]);
+ String path = "/app";
+ for (int i = 0; i < 64; i++) {
+ path += "/n";
+ support.addNode(tree, path, new byte[1]);
+ }
+
+ assertEquals(" /app\n children: 64\n data: 66\n"
+ + "-- /app/n\n-- children: 63\n-- data: 64",
+ entries(summarize(tree, "/app", "1")));
+ }
+
+ @Test
+ public void testSiblingOrderAndUtf8PayloadBytes() throws Exception {
+ DataTree tree = new DataTree();
+ support.addNode(tree, "/app", "\u00e9".getBytes(StandardCharsets.UTF_8));
+ support.addNode(tree, "/app/z", null);
+ support.addNode(tree, "/app/z/leaf", new byte[1]);
+ support.addNode(tree, "/app/a", null);
+ support.addNode(tree, "/app/a/leaf", new byte[3]);
+
+ assertEquals(" /app\n children: 4\n data: 6\n"
+ + "-- /app/a\n-- children: 1\n-- data: 3\n"
+ + "-- /app/z\n-- children: 1\n-- data: 1",
+ entries(summarize(tree, "/app", "0")));
+ }
+
+ @Test
+ public void testEphemeralDescendantsAreIncluded() throws Exception {
+ DataTree tree = new DataTree();
+ support.addNode(tree, "/app", new byte[2]);
+ tree.createNode("/app/ephemeral", new byte[7], ZooDefs.Ids.OPEN_ACL_UNSAFE, 0x123L, -1, 1, 1);
+
+ assertEquals(" /app\n children: 1\n data: 9", entries(summarize(tree, "/app", "0")));
+ }
+
+ @ParameterizedTest
+ @EnumSource(StreamMode.class)
+ public void testCompressedSnapshotsWithAndWithoutDigest(StreamMode mode) throws Exception {
+ for (boolean digest : new boolean[]{false, true}) {
+ File snapshot = support.snapshot(tree(), mode, digest);
+ byte[] before = Files.readAllBytes(snapshot.toPath());
+
+ String output = run(snapshot.toString(), "/app", "1").success();
+
+ assertEquals(" /app\n children: 5\n data: 17\n"
+ + "-- /app/branch\n-- children: 2\n-- data: 8", entries(output));
+ assertArrayEquals(before, Files.readAllBytes(snapshot.toPath()));
+ }
+ }
+
+ @Test
+ public void testCheckedInSnapshotFixture() throws Exception {
+ String output = run(support.fixture("snapshot.2").toString(), "/", "0").success();
+
+ assertEquals(" /\n children: 3\n data: 5000\n"
+ + "-- /zookeeper\n-- children: 1\n-- data: 0", entries(output));
+ }
+
+ @Test
+ public void testInvalidArguments() throws Exception {
+ File snapshot = support.snapshot(tree(), StreamMode.CHECKED, true);
+ run().invalidInvocation();
+ run(snapshot.toString(), "/app").invalidInvocation();
+ run(snapshot.toString(), "/app", "0", "extra").invalidInvocation();
+ for (String invalid : Arrays.asList("-1", "NaN", "2147483648")) {
+ run(snapshot.toString(), "/app", invalid).invalidInvocation();
+ }
+ }
+
+ @Test
+ public void testInvalidZnodePathsAndFiles() throws Exception {
+ File snapshot = support.snapshot(tree(), StreamMode.CHECKED, true);
+ for (String invalid : Arrays.asList("", "app", "/app/", "/app//leaf", "/app/..", "/missing")) {
+ SnapshotToolTestSupport.Result result = run(snapshot.toString(), invalid, "0");
+ result.invalidInvocation();
+ assertThat(result.output, not(containsString("NullPointerException")));
+ }
+ run(new File(support.directory, "missing").toString(), "/", "0").invalidInvocation();
+ run(support.directory.toString(), "/", "0").invalidInvocation();
+ }
+
+ @Test
+ public void testRunReportsInvalidInputAndReadFailure() throws Exception {
+ SnapshotRecursiveSummary summary = new SnapshotRecursiveSummary();
+ File snapshot = support.snapshot(tree(), StreamMode.CHECKED, true);
+ assertThrows(IllegalArgumentException.class, () -> summary.run(snapshot.toString(), "/missing", 0));
+ assertThrows(IllegalArgumentException.class, () -> summary.run(snapshot.toString(), "/", -1));
+ File corrupt = support.corruptSnapshots().get(0);
+ assertThrows(IOException.class, () -> summary.run(corrupt.toString(), "/", 0));
+ }
+
+ @Test
+ public void testCorruptSnapshots() throws Exception {
+ for (File corrupt : support.corruptSnapshots()) {
+ SnapshotToolTestSupport.Result result = run(corrupt.toString(), "/", "0");
+ result.readFailure();
+ assertThat(result.output, not(containsString("children:")));
+ }
+ }
+
+ @Test
+ public void testShellLauncher() throws Exception {
+ assumeFalse(System.getProperty("os.name").startsWith("Windows"));
+ File snapshot = support.snapshot(tree(), StreamMode.GZIP, true);
+ for (String flags : Arrays.asList("", "-Xms32m -Xmx128m")) {
+ String output = support.runLauncher("zkSnapshotRecursiveSummaryToolkit.sh", flags,
+ snapshot.toString(), "/app", "1").success();
+ assertEquals(" /app\n children: 5\n data: 17\n"
+ + "-- /app/branch\n-- children: 2\n-- data: 8", entries(output));
+ }
+ support.runLauncher("zkSnapshotRecursiveSummaryToolkit.sh", "").invalidInvocation();
+ }
+
+ private DataTree tree() throws Exception {
+ DataTree tree = new DataTree();
+ support.addNode(tree, "/app", new byte[2]);
+ support.addNode(tree, "/app/branch", new byte[3]);
+ support.addNode(tree, "/app/branch/deep", null);
+ support.addNode(tree, "/app/branch/deep/leaf", new byte[5]);
+ support.addNode(tree, "/app/empty", null);
+ support.addNode(tree, "/app/leaf", new byte[7]);
+ return tree;
+ }
+
+ private String summarize(DataTree tree, String path, String depth) throws Exception {
+ File snapshot = support.snapshot(tree, StreamMode.CHECKED, true);
+ return run(snapshot.toString(), path, depth).success();
+ }
+
+ private String entries(String output) {
+ return Arrays.stream(output.split("\\r?\\n"))
+ .filter(line -> line.matches("(--)* (/.*| (children|data): [0-9]+)"))
+ .collect(Collectors.joining("\n"));
+ }
+
+ private SnapshotToolTestSupport.Result run(String... args) throws Exception {
+ return support.run("org.apache.zookeeper.server.SnapshotRecursiveSummary", "", args);
+ }
+
+}