diff --git a/bin/zkSnapshotComparer.cmd b/bin/zkSnapshotComparer.cmd index 732af9352da..9701d00db7b 100755 --- a/bin/zkSnapshotComparer.cmd +++ b/bin/zkSnapshotComparer.cmd @@ -20,5 +20,4 @@ call "%~dp0zkEnv.cmd" set ZOOMAIN=org.apache.zookeeper.server.SnapshotComparer call %JAVA% -cp "%CLASSPATH%" %ZOOMAIN% %* -endlocal - +endlocal & exit /b %ERRORLEVEL% diff --git a/bin/zkSnapshotRecursiveSummaryToolkit.cmd b/bin/zkSnapshotRecursiveSummaryToolkit.cmd new file mode 100644 index 00000000000..850704a3719 --- /dev/null +++ b/bin/zkSnapshotRecursiveSummaryToolkit.cmd @@ -0,0 +1,23 @@ +@echo off +REM Licensed to the Apache Software Foundation (ASF) under one or more +REM contributor license agreements. See the NOTICE file distributed with +REM this work for additional information regarding copyright ownership. +REM The ASF licenses this file to You under the Apache License, Version 2.0 +REM (the "License"); you may not use this file except in compliance with +REM the License. You may obtain a copy of the License at +REM +REM http://www.apache.org/licenses/LICENSE-2.0 +REM +REM Unless required by applicable law or agreed to in writing, software +REM distributed under the License is distributed on an "AS IS" BASIS, +REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +REM See the License for the specific language governing permissions and +REM limitations under the License. + +setlocal +call "%~dp0zkEnv.cmd" + +set ZOOMAIN=org.apache.zookeeper.server.SnapshotRecursiveSummary +call %JAVA% -cp "%CLASSPATH%" %ZOOMAIN% %* + +endlocal & exit /b %ERRORLEVEL% diff --git a/bin/zkSnapshotRecursiveSummaryToolkit.sh b/bin/zkSnapshotRecursiveSummaryToolkit.sh new file mode 100755 index 00000000000..d43be95a84c --- /dev/null +++ b/bin/zkSnapshotRecursiveSummaryToolkit.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + +# 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. + +ZOOBIN="${BASH_SOURCE-$0}" +ZOOBIN="$(dirname "${ZOOBIN}")" +ZOOBINDIR="$(cd "${ZOOBIN}"; pwd)" + +if [ -e "$ZOOBIN/../libexec/zkEnv.sh" ]; then + . "$ZOOBINDIR"/../libexec/zkEnv.sh +else + . "$ZOOBINDIR"/zkEnv.sh +fi + +"$JAVA" -cp "$CLASSPATH" $JVMFLAGS \ + org.apache.zookeeper.server.SnapshotRecursiveSummary "$@" diff --git a/zookeeper-docs/src/main/resources/markdown/zookeeperTools.md b/zookeeper-docs/src/main/resources/markdown/zookeeperTools.md index 5141766d75c..55d4f9ef0eb 100644 --- a/zookeeper-docs/src/main/resources/markdown/zookeeperTools.md +++ b/zookeeper-docs/src/main/resources/markdown/zookeeperTools.md @@ -24,6 +24,7 @@ limitations under the License. * [zkTxnLogToolkit.sh](#zkTxnLogToolkit) * [zkSnapShotToolkit.sh](#zkSnapShotToolkit) * [zkSnapshotComparer.sh](#zkSnapshotComparer) + * [zkSnapshotRecursiveSummaryToolkit.sh](#zkSnapshotRecursiveSummaryToolkit) * [Benchmark](#Benchmark) * [YCSB](#YCSB) @@ -228,12 +229,20 @@ The delta includes specific znode paths added, updated, deleted comparing one sn It's useful in use cases that involve snapshot analysis, such as offline data consistency checking, and data trending analysis (e.g. what's growing under which zNode path during when). -This tool only outputs information about permanent nodes, ignoring both sessions and ephemeral nodes. +This tool includes ephemeral znodes present in the snapshot, but does not report +session records or compare payload contents, ACLs, versions or other metadata. It provides two tuning parameters to help filter out noise: 1. `--nodes` Threshold number of children added/removed; 2. `--bytes` Threshold number of bytes added/removed. +Both thresholds are required, non-negative integers up to 2147483647. A path is +printed when either absolute difference is **strictly greater** than its +threshold. Deltas are **right minus left**. Subtree byte totals include the +node's own payload; descendant counts exclude the node itself. Null data +contributes zero bytes, so a zero-byte leaf present in only one snapshot is +filtered even with both thresholds set to zero. + #### Locate Snapshots Snapshots can be found in [Zookeeper Data Directory](zookeeperAdmin.html#The+Data+Directory) which configured in [conf/zoo.cfg](zookeeperStarted.html#sc_InstallingSingleMode) when set up Zookeeper server. @@ -430,6 +439,62 @@ All layers compared. Or use `^c` to exit interactive mode anytime. +End of input also exits interactive mode. Entering `/` compares the root's +immediate children; comparison lines retain the empty label for the root. + + + +### zkSnapshotRecursiveSummaryToolkit.sh + +Recursively summarize the payload sizes and descendant counts in one snapshot +subtree: + +```bash +bin/zkSnapshotRecursiveSummaryToolkit.sh snapshot.1 /app 1 +``` + +Usage: `SnapshotRecursiveSummary `. +The starting node must be an existing absolute znode path. The maximum depth is +a non-negative integer: 0 prints every non-leaf node, 1 prints the starting +node and its non-leaf children, 2 adds another level, and so on. +**Depth limits output only, not traversal or totals.** Siblings are printed +alphabetically. + +`children` counts all descendants, not just immediate children. `data` is the +sum of payload bytes for the node itself and all descendants, including +ephemeral nodes. Null data contributes zero bytes. Leaves contribute to their +ancestors' totals but are not printed; selecting a leaf produces no summary +entries. + +For example, if `/app` has 2 payload bytes, `/app/branch` has 3, and +`/app/branch/leaf` has 5, the summary is: + +```text + /app + children: 2 + data: 10 +-- /app/branch +-- children: 1 +-- data: 8 +``` + +#### Snapshot analysis limitations + +Both tools run offline and do not modify snapshot files. They support +uncompressed, `.gz` and `.snappy` snapshots, including snapshots without a +digest and mixed compression formats in the comparer. They validate snapshot +seals and report unreadable or corrupt input rather than silently producing a +successful analysis. Invalid arguments, file paths or summary starting paths +exit with code 2; snapshot read failures exit with code 1. Windows launchers +with the same names and a `.cmd` extension are included. The launchers use the +existing `zkEnv` configuration. + +Neither tool compares payload contents, ACLs, versions or other znode metadata. +**Equal sizes/counts do not prove identical contents.** Snapshots may be fuzzy: +these tools do not replay transaction logs, reconstruct point-in-time state, +or establish transaction-consistent equality. Both tools load the snapshot +into memory. Recursive traversal visits the full selected subtree even when +summary output depth is limited; very deep trees may exceed the JVM stack. diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/SnapshotComparer.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/SnapshotComparer.java index 84d265c81d7..288eac67794 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/SnapshotComparer.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/SnapshotComparer.java @@ -19,6 +19,8 @@ package org.apache.zookeeper.server; import java.io.File; +import java.io.IOException; +import java.io.PushbackInputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; @@ -27,6 +29,7 @@ import java.util.List; import java.util.Map; import java.util.Scanner; +import java.util.Set; import java.util.zip.CheckedInputStream; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; @@ -36,6 +39,7 @@ import org.apache.commons.cli.ParseException; import org.apache.jute.BinaryInputArchive; import org.apache.jute.InputArchive; +import org.apache.zookeeper.ZKUtil; import org.apache.zookeeper.server.persistence.FileSnap; import org.apache.zookeeper.server.persistence.SnapStream; import org.apache.zookeeper.util.ServiceUtils; @@ -44,7 +48,8 @@ * SnapshotComparer is a tool that loads and compares two snapshots with configurable threshold and various filters, and outputs information about the delta. * The delta includes specific znode paths added, updated, deleted comparing one snapshot to another. * It's useful in use cases that involve snapshot analysis, such as offline data consistency checking, and data trending analysis (e.g. what's growing under which zNode path during when). - * Only outputs information about permanent nodes, ignoring both sessions and ephemeral nodes. + * Includes ephemeral nodes, but does not compare sessions, payload contents, ACLs or other metadata. + * Equal sizes and counts do not establish identical contents or transaction-consistent state. */ public class SnapshotComparer { private final Options options; @@ -109,26 +114,47 @@ private void usage() { ""); } - public static void main(String[] args) throws Exception { + public static void main(String[] args) { SnapshotComparer app = new SnapshotComparer(); - app.compareSnapshots(args); + try { + app.compareSnapshots(args); + } catch (IOException e) { + System.err.println("Unable to read snapshot: " + e.getMessage()); + ServiceUtils.requestSystemExit(ExitCode.UNEXPECTED_ERROR.getValue()); + } } - private void compareSnapshots(String[] args) throws Exception { + private void compareSnapshots(String[] args) throws IOException { CommandLine parsedOptions; + File left; + File right; + int byteThreshold; + int nodeThreshold; try { parsedOptions = new DefaultParser().parse(options, args); - } catch (ParseException e) { + if (!parsedOptions.getArgList().isEmpty()) { + throw new IllegalArgumentException("Unexpected arguments: " + parsedOptions.getArgList()); + } + left = (File) parsedOptions.getParsedOptionValue(leftOption); + right = (File) parsedOptions.getParsedOptionValue(rightOption); + byteThreshold = Integer.parseInt(parsedOptions.getOptionValue(byteThresholdOption)); + nodeThreshold = Integer.parseInt(parsedOptions.getOptionValue(nodeThresholdOption)); + if (byteThreshold < 0 || nodeThreshold < 0) { + throw new IllegalArgumentException("Thresholds must be non-negative integers."); + } + for (File file : new File[]{left, right}) { + String error = ZKUtil.validateFileInput(file.toString()); + if (error != null) { + throw new IllegalArgumentException(error); + } + } + } catch (ParseException | IllegalArgumentException e) { System.err.println(e.getMessage()); usage(); ServiceUtils.requestSystemExit(ExitCode.INVALID_INVOCATION.getValue()); return; } - File left = (File) parsedOptions.getParsedOptionValue(leftOption); - File right = (File) parsedOptions.getParsedOptionValue(rightOption); - int byteThreshold = Integer.parseInt((String) parsedOptions.getParsedOptionValue(byteThresholdOption)); - int nodeThreshold = Integer.parseInt((String) parsedOptions.getParsedOptionValue(nodeThresholdOption)); boolean debug = parsedOptions.hasOption(debugOption); boolean interactive = parsedOptions.hasOption(interactiveOption); System.out.println("Successfully parsed options!"); @@ -172,15 +198,18 @@ public TreeNode(String label, long size) { this.children = new ArrayList(); } - void populateChildren(String path, DataTree dataTree, TreeInfo treeInfo) throws Exception { + void populateChildren(String path, DataTree dataTree, TreeInfo treeInfo) { populateChildren(path, dataTree, treeInfo, 1); } - void populateChildren(String path, DataTree dataTree, TreeInfo treeInfo, int currentDepth) throws Exception { - List childLabels = null; - childLabels = dataTree.getChildren(path, null, null); + void populateChildren(String path, DataTree dataTree, TreeInfo treeInfo, int currentDepth) { + DataNode node = dataTree.getNode(path); + Set childLabels; + synchronized (node) { + childLabels = node.getChildren(); + } - if (childLabels != null && !childLabels.isEmpty()) { + if (!childLabels.isEmpty()) { for (String childName : childLabels){ String childPath = path + "/" + childName; DataNode childNode = dataTree.getNode(childPath); @@ -211,13 +240,19 @@ void populateChildren(String path, DataTree dataTree, TreeInfo treeInfo, int cur List> nodesAtDepths = new ArrayList>(); Map nodesByName = new HashMap(); - TreeInfo(File snapshot) throws Exception { + TreeInfo(File snapshot) throws IOException { + long beginning = System.nanoTime(); DataTree dataTree = getSnapshot(snapshot); + System.out.println(String.format("Deserialized snapshot in %s in %f seconds", + snapshot.getName(), (System.nanoTime() - beginning) / 1_000_000_000.0)); count = 0; - long beginning = System.nanoTime(); + beginning = System.nanoTime(); DataNode root = dataTree.getNode(""); - long size = root.data == null ? 0 : root.data.length; + long size; + synchronized (root) { + size = root.data == null ? 0 : root.data.length; + } this.root = new TreeNode("", size); // Construct TreeInfo tree from DataTree this.root.populateChildren("", dataTree, this); @@ -256,21 +291,40 @@ public static Comparator MakeAlphabeticComparator() { /** * Parse a Zookeeper snapshot file to DataTree * @param file the snapshot file - * @throws Exception + * @throws IOException if the snapshot cannot be read or its seals are invalid */ - private static DataTree getSnapshot(File file) throws Exception { - FileSnap fileSnap = new FileSnap(null); - DataTree dataTree = new DataTree(); - Map sessions = new HashMap(); - CheckedInputStream snapIS = SnapStream.getInputStream(file); - - long beginning = System.nanoTime(); - InputArchive ia = BinaryInputArchive.getArchive(snapIS); - fileSnap.deserialize(dataTree, sessions, ia); - long end = System.nanoTime(); - System.out.println(String.format("Deserialized snapshot in %s in %f seconds", file.getName(), - (((double) (end - beginning) / 1000000)) / 1000)); - return dataTree; + static DataTree getSnapshot(File file) throws IOException { + try (CheckedInputStream stream = SnapStream.getInputStream(file); + PushbackInputStream input = new PushbackInputStream(stream)) { + InputArchive archive = BinaryInputArchive.getArchive(input); + DataTree dataTree = new DataTree(); + new FileSnap(null).deserialize(dataTree, new HashMap(), archive); + checkSealIntegrity(stream, archive); + + // Distinguish an absent digest in older snapshots from a truncated digest. + int next = input.read(); + if (next != -1) { + input.unread(next); + dataTree.new ZxidDigest().deserialize(archive); + checkSealIntegrity(stream, archive); + if (input.read() != -1) { + throw new IOException("Unexpected data after snapshot"); + } + } + return dataTree; + } catch (IOException | NumberFormatException e) { + throw new IOException(file + ": " + e, e); + } + } + + private static void checkSealIntegrity(CheckedInputStream stream, InputArchive archive) throws IOException { + // SnapStream's seal checker is package-private on this branch. + long checksum = stream.getChecksum().getValue(); + long expected = archive.readLong("val"); + String path = archive.readString("path"); + if (checksum != expected || !"/".equals(path)) { + throw new IOException("CRC corruption or invalid snapshot seal"); + } } private static void printThresholdInfo(int byteThreshold, int nodeThreshold) { @@ -288,49 +342,55 @@ private static void compareTrees(TreeInfo left, TreeInfo right, int byteThreshol } } else { // interactive mode - Scanner scanner = new Scanner(System.in); - int currentDepth = 0; - while (currentDepth < maxDepth) { - System.out.println(String.format("Current depth is %d", currentDepth)); - System.out.println("- Press enter to move to print current depth layer;\n- Type a number to jump to and print all nodes at a given depth;\n- Enter an ABSOLUTE path to print the immediate subtree of a node. Path must start with '/'."); - String input = scanner.nextLine(); - printThresholdInfo(byteThreshold, nodeThreshold); - if (input.isEmpty()) { - // input is Enter - System.out.println(String.format("Analysis for depth %d", currentDepth)); - compareLine(left, right, currentDepth, byteThreshold, nodeThreshold, debug, interactive); - currentDepth++; - } else { - // input is a path - if (input.startsWith("/")){ - System.out.println(String.format("Analysis for node %s", input)); - compareSubtree(left, right, input, byteThreshold, nodeThreshold, debug, interactive); + try (Scanner scanner = new Scanner(System.in)) { + int currentDepth = 0; + while (currentDepth < maxDepth) { + System.out.println(String.format("Current depth is %d", currentDepth)); + System.out.println("- Press enter to move to print current depth layer;\n- Type a number to jump to and print all nodes at a given depth;\n- Enter an ABSOLUTE path to print the immediate subtree of a node. Path must start with '/'."); + if (!scanner.hasNextLine()) { + System.out.println("End of input."); + return; + } + String input = scanner.nextLine(); + printThresholdInfo(byteThreshold, nodeThreshold); + if (input.isEmpty()) { + // input is Enter + System.out.println(String.format("Analysis for depth %d", currentDepth)); + compareLine(left, right, currentDepth, byteThreshold, nodeThreshold, debug, interactive); + currentDepth++; } else { - // input is a number - try { - int depth = Integer.parseInt(input); - if (depth < 0 || depth >= maxDepth) { - System.out.println(String.format("Depth must be in range [%d, %d]", 0, maxDepth - 1)); - continue; + // input is a path + if (input.startsWith("/")){ + System.out.println(String.format("Analysis for node %s", input)); + compareSubtree(left, right, input, byteThreshold, nodeThreshold, debug, interactive); + } else { + // input is a number + try { + int depth = Integer.parseInt(input); + if (depth < 0 || depth >= maxDepth) { + System.out.println(String.format("Depth must be in range [%d, %d]", 0, maxDepth - 1)); + continue; + } + currentDepth = depth; + System.out.println(String.format("Analysis for depth %d", currentDepth)); + compareLine(left, right, currentDepth, byteThreshold, nodeThreshold, debug, interactive); + } catch (NumberFormatException ex) { + // input is invalid + System.out.println(String.format("Input %s is not valid. Depth must be in range [%d, %d]. Path must be an absolute path which starts with '/'.", input, 0, maxDepth - 1)); } - currentDepth = depth; - System.out.println(String.format("Analysis for depth %d", currentDepth)); - compareLine(left, right, currentDepth, byteThreshold, nodeThreshold, debug, interactive); - } catch (NumberFormatException ex) { - // input is invalid - System.out.println(String.format("Input %s is not valid. Depth must be in range [%d, %d]. Path must be an absolute path which starts with '/'.", input, 0, maxDepth - 1)); } } + System.out.println(""); } - System.out.println(""); } } System.out.println("All layers compared."); } private static void compareSubtree(TreeInfo left, TreeInfo right, String path, int byteThreshold, int nodeThreshold, boolean debug, boolean interactive) { - TreeInfo.TreeNode leftRoot = left.nodesByName.get(path); - TreeInfo.TreeNode rightRoot = right.nodesByName.get(path); + String label = "/".equals(path) ? "" : path; + TreeInfo.TreeNode leftRoot = left.nodesByName.get(label); + TreeInfo.TreeNode rightRoot = right.nodesByName.get(label); List leftList = leftRoot == null ? new ArrayList() : leftRoot.children; List rightList = rightRoot == null ? new ArrayList() : 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); + } + +}