You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@zookeeper.apache.org by eo...@apache.org on 2020/02/28 09:58:44 UTC

[zookeeper] branch master updated: ZOOKEEPER-3427: Introduce SnapshotComparer that assists debugging with snapshots.

This is an automated email from the ASF dual-hosted git repository.

eolivelli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/zookeeper.git


The following commit(s) were added to refs/heads/master by this push:
     new f90060b  ZOOKEEPER-3427: Introduce SnapshotComparer that assists debugging with snapshots.
f90060b is described below

commit f90060b83da4bfcca58ada93a57fedb40a069387
Author: Michael Han <lh...@twitter.com>
AuthorDate: Fri Feb 28 10:58:24 2020 +0100

    ZOOKEEPER-3427: Introduce SnapshotComparer that assists debugging with snapshots.
    
    SnapshotComparer is a tool that loads and compares two snapshots, with configurable threshold and various filters. 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).
    
    Author: Michael Han <lh...@twitter.com>
    
    Reviewers: Enrico Olivelli <eo...@apache.org>, Justin Ling Mao <ma...@sina.com>
    
    Closes #984 from hanm/twitter/cecec485cab86b5d9d885521e1ec3d766a336302
---
 bin/zkSnapshotComparer.cmd                         |  24 ++
 bin/zkSnapshotComparer.sh                          |  36 ++
 .../src/main/resources/markdown/zookeeperTools.md  | 212 ++++++++++
 .../apache/zookeeper/server/SnapshotComparer.java  | 459 +++++++++++++++++++++
 4 files changed, 731 insertions(+)

diff --git a/bin/zkSnapshotComparer.cmd b/bin/zkSnapshotComparer.cmd
new file mode 100755
index 0000000..732af93
--- /dev/null
+++ b/bin/zkSnapshotComparer.cmd
@@ -0,0 +1,24 @@
+@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.SnapshotComparer
+call %JAVA% -cp "%CLASSPATH%" %ZOOMAIN% %*
+
+endlocal
+
diff --git a/bin/zkSnapshotComparer.sh b/bin/zkSnapshotComparer.sh
new file mode 100755
index 0000000..b284c90
--- /dev/null
+++ b/bin/zkSnapshotComparer.sh
@@ -0,0 +1,36 @@
+#!/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.
+
+#
+# If this scripted is run out of /usr/bin or some other system bin directory
+# it should be linked to and not copied. Things like java jar files are found
+# relative to the canonical path of this script.
+#
+
+# use POSIX interface, symlink is followed automatically
+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.SnapshotComparer "$@"
diff --git a/zookeeper-docs/src/main/resources/markdown/zookeeperTools.md b/zookeeper-docs/src/main/resources/markdown/zookeeperTools.md
index 475a528..05d7c66 100644
--- a/zookeeper-docs/src/main/resources/markdown/zookeeperTools.md
+++ b/zookeeper-docs/src/main/resources/markdown/zookeeperTools.md
@@ -23,6 +23,7 @@ limitations under the License.
     * [zkCleanup.sh](#zkCleanup)
     * [zkTxnLogToolkit.sh](#zkTxnLogToolkit)
     * [zkSnapShotToolkit.sh](#zkSnapShotToolkit)
+    * [zkSnapshotComparer.sh](#zkSnapshotComparer)
     
 * [Testing](#Testing)
     * [Jepsen Test](#jepsen-test)
@@ -205,6 +206,217 @@ USAGE: SnapshotFormatter [-d|-json] snapshot_file
 [[1,0,{"progname":"SnapshotFormatter.java","progver":"0.01","timestamp":1559788148637},[{"name":"\/","asize":0,"dsize":0,"dev":0,"ino":1001},[{"name":"zookeeper","asize":0,"dsize":0,"dev":0,"ino":1002},{"name":"config","asize":0,"dsize":0,"dev":0,"ino":1003},[{"name":"quota","asize":0,"dsize":0,"dev":0,"ino":1004},[{"name":"test","asize":0,"dsize":0,"dev":0,"ino":1005},{"name":"zookeeper_limits","asize":52,"dsize":52,"dev":0,"ino":1006},{"name":"zookeeper_stats","asize":15,"dsize":15,"de [...]
 ```
 
+<a name="zkSnapshotComparer"></a>
+
+### zkSnapshotComparer.sh
+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).
+
+This tool only outputs information about permanent nodes, ignoring both sessions and ephemeral nodes.
+
+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.
+
+#### 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. 
+
+#### Supported Snapshot Formats
+This tool supports uncompressed snapshot format, and compressed snapshot file formats: `snappy` and `gz`. Snapshots with different formats can be compared using this tool directly without decompression.
+
+#### Running the Tool
+Running the tool with no command line argument or an unrecognized argument, it outputs the following help page:
+
+```
+usage: java -cp <classPath> org.apache.zookeeper.server.SnapshotComparer
+ -b,--bytes <BYTETHRESHOLD>   (Required) The node data delta size threshold, in bytes, for printing the node.
+ -d,--debug                   Use debug output.
+ -i,--interactive             Enter interactive mode.
+ -l,--left <LEFT>             (Required) The left snapshot file.
+ -n,--nodes <NODETHRESHOLD>   (Required) The descendant node delta size threshold, in nodes, for printing the node.
+ -r,--right <RIGHT>           (Required) The right snapshot file.
+```
+Example Command:
+
+```
+./bin/zkSnapshotComparer.sh -l /zookeeper-data/backup/snapshot.d.snappy -r /zookeeper-data/backup/snapshot.44 -b 2 -n 1
+```
+
+Example Output:
+```
+...
+Deserialized snapshot in snapshot.44 in 0.002741 seconds
+Processed data tree in 0.000361 seconds
+Node count: 10
+Total size: 0
+Max depth: 4
+Count of nodes at depth 0: 1
+Count of nodes at depth 1: 2
+Count of nodes at depth 2: 4
+Count of nodes at depth 3: 3
+
+Node count: 22
+Total size: 2903
+Max depth: 5
+Count of nodes at depth 0: 1
+Count of nodes at depth 1: 2
+Count of nodes at depth 2: 4
+Count of nodes at depth 3: 7
+Count of nodes at depth 4: 8
+
+Printing analysis for nodes difference larger than 2 bytes or node count difference larger than 1.
+Analysis for depth 0
+Node  found in both trees. Delta: 2903 bytes, 12 descendants
+Analysis for depth 1
+Node /zk_test found in both trees. Delta: 2903 bytes, 12 descendants
+Analysis for depth 2
+Node /zk_test/gz found in both trees. Delta: 730 bytes, 3 descendants
+Node /zk_test/snappy found in both trees. Delta: 2173 bytes, 9 descendants
+Analysis for depth 3
+Node /zk_test/gz/12345 found in both trees. Delta: 9 bytes, 1 descendants
+Node /zk_test/gz/a found only in right tree. Descendant size: 721. Descendant count: 0
+Node /zk_test/snappy/anotherTest found in both trees. Delta: 1738 bytes, 2 descendants
+Node /zk_test/snappy/test_1 found only in right tree. Descendant size: 344. Descendant count: 3
+Node /zk_test/snappy/test_2 found only in right tree. Descendant size: 91. Descendant count: 2
+Analysis for depth 4
+Node /zk_test/gz/12345/abcdef found only in right tree. Descendant size: 9. Descendant count: 0
+Node /zk_test/snappy/anotherTest/abc found only in right tree. Descendant size: 1738. Descendant count: 0
+Node /zk_test/snappy/test_1/a found only in right tree. Descendant size: 93. Descendant count: 0
+Node /zk_test/snappy/test_1/b found only in right tree. Descendant size: 251. Descendant count: 0
+Node /zk_test/snappy/test_2/xyz found only in right tree. Descendant size: 33. Descendant count: 0
+Node /zk_test/snappy/test_2/y found only in right tree. Descendant size: 58. Descendant count: 0
+All layers compared.
+```
+
+#### Interactive Mode
+Use "-i" or "--interactive" to enter interactive mode:
+```
+./bin/zkSnapshotComparer.sh -l /zookeeper-data/backup/snapshot.d.snappy -r /zookeeper-data/backup/snapshot.44 -b 2 -n 1 -i
+```
+
+There are three options to proceed:
+```
+- Press enter to move to print current depth layer;
+- Type a number to jump to and print all nodes at a given depth;
+- Enter an ABSOLUTE path to print the immediate subtree of a node. Path must start with '/'.
+```
+
+Note: As indicated by the interactive messages, the tool only shows analysis on the result that filtered by tuning parameters bytes threshold and nodes threshold.  
+
+Press enter to print current depth layer:
+
+```
+Current depth is 0
+Press enter to move to print current depth layer;
+...
+Printing analysis for nodes difference larger than 2 bytes or node count difference larger than 1.
+Analysis for depth 0
+Node  found in both trees. Delta: 2903 bytes, 12 descendants
+```
+
+Type a number to jump to and print all nodes at a given depth:
+
+(Jump forward)
+
+```
+Current depth is 1
+...
+Type a number to jump to and print all nodes at a given depth;
+...
+3
+Printing analysis for nodes difference larger than 2 bytes or node count difference larger than 1.
+Analysis for depth 3
+Node /zk_test/gz/12345 found in both trees. Delta: 9 bytes, 1 descendants
+Node /zk_test/gz/a found only in right tree. Descendant size: 721. Descendant count: 0
+Filtered node /zk_test/gz/anotherOne of left size 0, right size 0
+Filtered right node /zk_test/gz/b of size 0
+Node /zk_test/snappy/anotherTest found in both trees. Delta: 1738 bytes, 2 descendants
+Node /zk_test/snappy/test_1 found only in right tree. Descendant size: 344. Descendant count: 3
+Node /zk_test/snappy/test_2 found only in right tree. Descendant size: 91. Descendant count: 2
+```
+
+(Jump back)
+
+```
+Current depth is 3
+...
+Type a number to jump to and print all nodes at a given depth;
+...
+0
+Printing analysis for nodes difference larger than 2 bytes or node count difference larger than 1.
+Analysis for depth 0
+Node  found in both trees. Delta: 2903 bytes, 12 descendants
+```
+
+Out of range depth is handled:
+
+```
+Current depth is 1
+...
+Type a number to jump to and print all nodes at a given depth;
+...
+10
+Printing analysis for nodes difference larger than 2 bytes or node count difference larger than 1.
+Depth must be in range [0, 4]
+```
+
+Enter an ABSOLUTE path to print the immediate subtree of a node:
+
+```
+Current depth is 3
+...
+Enter an ABSOLUTE path to print the immediate subtree of a node.
+/zk_test
+Printing analysis for nodes difference larger than 2 bytes or node count difference larger than 1.
+Analysis for node /zk_test
+Node /zk_test/gz found in both trees. Delta: 730 bytes, 3 descendants
+Node /zk_test/snappy found in both trees. Delta: 2173 bytes, 9 descendants
+```
+
+Invalid path is handled:
+
+```
+Current depth is 3
+...
+Enter an ABSOLUTE path to print the immediate subtree of a node.
+/non-exist-path
+Printing analysis for nodes difference larger than 2 bytes or node count difference larger than 1.
+Analysis for node /non-exist-path
+Path /non-exist-path is neither found in left tree nor right tree.
+```
+
+Invalid input is handled:
+```
+Current depth is 1
+- Press enter to move to print current depth layer;
+- Type a number to jump to and print all nodes at a given depth;
+- Enter an ABSOLUTE path to print the immediate subtree of a node. Path must start with '/'.
+12223999999999999999999999999999999999999
+Printing analysis for nodes difference larger than 2 bytes or node count difference larger than 1.
+Input 12223999999999999999999999999999999999999 is not valid. Depth must be in range [0, 4]. Path must be an absolute path which starts with '/'.
+```
+
+Exit interactive mode automatically when all layers are compared:
+
+```
+Printing analysis for nodes difference larger than 2 bytes or node count difference larger than 1.
+Analysis for depth 4
+Node /zk_test/gz/12345/abcdef found only in right tree. Descendant size: 9. Descendant count: 0
+Node /zk_test/snappy/anotherTest/abc found only in right tree. Descendant size: 1738. Descendant count: 0
+Filtered right node /zk_test/snappy/anotherTest/abcd of size 0
+Node /zk_test/snappy/test_1/a found only in right tree. Descendant size: 93. Descendant count: 0
+Node /zk_test/snappy/test_1/b found only in right tree. Descendant size: 251. Descendant count: 0
+Filtered right node /zk_test/snappy/test_1/c of size 0
+Node /zk_test/snappy/test_2/xyz found only in right tree. Descendant size: 33. Descendant count: 0
+Node /zk_test/snappy/test_2/y found only in right tree. Descendant size: 58. Descendant count: 0
+All layers compared.
+```
+
+Or use `^c` to exit interactive mode anytime.
+
 <a name="Testing"></a>
 
 ## Testing
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
new file mode 100644
index 0000000..d77261d
--- /dev/null
+++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/SnapshotComparer.java
@@ -0,0 +1,459 @@
+/**
+ * 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.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Scanner;
+import java.util.zip.CheckedInputStream;
+import org.apache.commons.cli.BasicParser;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.jute.BinaryInputArchive;
+import org.apache.jute.InputArchive;
+import org.apache.zookeeper.server.persistence.FileSnap;
+import org.apache.zookeeper.server.persistence.SnapStream;
+import org.apache.zookeeper.util.ServiceUtils;
+
+/**
+ * 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.
+ */
+public class SnapshotComparer {
+  private final Options options;
+  private static final String leftOption = "left";
+  private static final String rightOption = "right";
+  private static final String byteThresholdOption = "bytes";
+  private static final String nodeThresholdOption = "nodes";
+  private static final String debugOption = "debug";
+  private static final String interactiveOption = "interactive";
+
+  @SuppressWarnings("static")
+  private SnapshotComparer() {
+    options = new Options();
+    options.addOption(
+        OptionBuilder
+            .hasArg()
+            .isRequired(true)
+            .withLongOpt(leftOption)
+            .withDescription("(Required) The left snapshot file.")
+            .withArgName("LEFT")
+            .withType(File.class)
+            .create("l"));
+    options.addOption(
+        OptionBuilder
+            .hasArg()
+            .isRequired(true)
+            .withLongOpt(rightOption)
+            .withDescription("(Required) The right snapshot file.")
+            .withArgName("RIGHT")
+            .withType(File.class)
+            .create("r"));
+    options.addOption(
+        OptionBuilder
+            .hasArg()
+            .isRequired(true)
+            .withLongOpt(byteThresholdOption)
+            .withDescription("(Required) The node data delta size threshold, in bytes, for printing the node.")
+            .withArgName("BYTETHRESHOLD")
+            .withType(String.class)
+            .create("b"));
+    options.addOption(
+        OptionBuilder
+            .hasArg()
+            .isRequired(true)
+            .withLongOpt(nodeThresholdOption)
+            .withDescription("(Required) The descendant node delta size threshold, in nodes, for printing the node.")
+            .withArgName("NODETHRESHOLD")
+            .withType(String.class)
+            .create("n"));
+    options.addOption("d", debugOption, false, "Use debug output.");
+    options.addOption("i", interactiveOption, false, "Enter interactive mode.");
+  }
+
+  private void usage() {
+    HelpFormatter help = new HelpFormatter();
+
+    help.printHelp(
+        120,
+        "java -cp <classPath> " + SnapshotComparer.class.getName(),
+        "",
+        options,
+        "");
+  }
+
+  public static void main(String[] args) throws Exception {
+    SnapshotComparer app = new SnapshotComparer();
+    app.compareSnapshots(args);
+  }
+
+  private void compareSnapshots(String[] args) throws Exception {
+    CommandLine parsedOptions;
+    try {
+      parsedOptions = new BasicParser().parse(options, args);
+    } catch (ParseException 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!");
+    TreeInfo leftTree = new TreeInfo(left);
+    TreeInfo rightTree = new TreeInfo(right);
+
+    System.out.println(leftTree.toString());
+    System.out.println(rightTree.toString());
+
+    compareTrees(leftTree, rightTree, byteThreshold, nodeThreshold, debug, interactive);
+  }
+
+  private static class TreeInfo {
+    public static class TreeNode {
+      final String label;
+      final long size;
+      final List<TreeNode> children;
+      long descendantSize;
+      long descendantCount;
+
+      public static class AlphabeticComparator implements Comparator<TreeNode>, Serializable {
+        private static final long serialVersionUID = 2601197766392565593L;
+
+        public int compare(TreeNode left, TreeNode right) {
+          if (left == right) {
+            return 0;
+          }
+          if (left == null) {
+            return -1;
+          }
+          if (right == null) {
+            return 1;
+          }
+          return left.label.compareTo(right.label);
+        }
+      }
+
+      public TreeNode(String label, long size) {
+        this.label = label;
+        this.size = size;
+        this.children = new ArrayList<TreeNode>();
+      }
+
+      void populateChildren(String path, DataTree dataTree, TreeInfo treeInfo) throws Exception {
+        populateChildren(path, dataTree, treeInfo, 1);
+      }
+
+      void populateChildren(String path, DataTree dataTree, TreeInfo treeInfo, int currentDepth) throws Exception {
+        List<String> childLabels = null;
+        childLabels = dataTree.getChildren(path, null, null);
+
+        if (childLabels != null && !childLabels.isEmpty()) {
+          for (String childName : childLabels){
+            String childPath = path + "/" + childName;
+            DataNode childNode = dataTree.getNode(childPath);
+            long size;
+            synchronized (childNode) {
+              size = childNode.data == null ? 0 : childNode.data.length;
+            }
+            TreeNode childTreeNode = new TreeNode(childPath, size);
+            childTreeNode.populateChildren(childPath, dataTree, treeInfo, currentDepth + 1);
+            children.add(childTreeNode);
+          }
+        }
+        descendantSize = 0;
+        descendantCount = 0;
+        for (TreeNode child : children) {
+          descendantSize += child.descendantSize;
+          descendantCount += child.descendantCount;
+        }
+        descendantSize += this.size;
+        descendantCount += this.children.size();
+
+        treeInfo.registerNode(this, currentDepth);
+      }
+    }
+
+    final TreeNode root;
+    long count;
+    List<ArrayList<TreeNode>> nodesAtDepths = new ArrayList<ArrayList<TreeNode>>();
+    Map<String, TreeNode> nodesByName = new HashMap<String, TreeNode>();
+
+    TreeInfo(File snapshot) throws Exception {
+      DataTree dataTree = getSnapshot(snapshot);
+
+      count = 0;
+      long beginning = System.nanoTime();
+      DataNode root = dataTree.getNode("");
+      long size = root.data == null ? 0 : root.data.length;
+      this.root = new TreeNode("", size);
+      // Construct TreeInfo tree from DataTree
+      this.root.populateChildren("", dataTree, this);
+      long end = System.nanoTime();
+
+      System.out.println(String.format("Processed data tree in %f seconds",
+          ((((double) end - beginning) / 1000000)) / 1000));
+    }
+
+    void registerNode(TreeNode node, int depth) {
+      while (depth > nodesAtDepths.size()) {
+        nodesAtDepths.add(new ArrayList<TreeNode>());
+      }
+      nodesAtDepths.get(depth - 1).add(node);
+      nodesByName.put(node.label, node);
+
+      this.count++;
+    }
+
+    public String toString() {
+      StringBuilder builder = new StringBuilder();
+      builder.append(String.format("Node count: %d%n", count));
+      builder.append(String.format("Total size: %d%n", root.descendantSize));
+      builder.append(String.format("Max depth: %d%n", nodesAtDepths.size()));
+      for (int i = 0; i < nodesAtDepths.size(); i++) {
+        builder.append(String.format("Count of nodes at depth %d: %d%n", i, nodesAtDepths.get(i).size()));
+      }
+      return builder.toString();
+    }
+
+    public static Comparator<TreeNode> MakeAlphabeticComparator() {
+      return new TreeNode.AlphabeticComparator();
+    }
+  }
+
+  /**
+   * Parse a Zookeeper snapshot file to DataTree
+   * @param file the snapshot file
+   * @throws Exception
+   */
+  private static DataTree getSnapshot(File file) throws Exception {
+    FileSnap fileSnap = new FileSnap(null);
+    DataTree dataTree = new DataTree();
+    Map<Long, Integer> sessions = new HashMap<Long, Integer>();
+    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;
+  }
+
+  private static void printThresholdInfo(int byteThreshold, int nodeThreshold) {
+    System.out.println(String.format("Printing analysis for nodes difference larger than %d bytes or node count difference larger than %d.", byteThreshold, nodeThreshold));
+  }
+
+  private static void compareTrees(TreeInfo left, TreeInfo right, int byteThreshold, int nodeThreshold, boolean debug, boolean interactive) {
+    int maxDepth = Math.max(left.nodesAtDepths.size(), right.nodesAtDepths.size());
+
+    if (!interactive) {
+      printThresholdInfo(byteThreshold, nodeThreshold);
+      for (int i = 0; i < maxDepth; i++) {
+        System.out.println(String.format("Analysis for depth %d", i));
+        compareLine(left, right, i, byteThreshold, nodeThreshold, debug, interactive);
+      }
+    } 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);
+          } 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));
+            }
+          }
+        }
+        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);
+
+    List<TreeInfo.TreeNode> leftList = leftRoot == null ? new ArrayList<TreeInfo.TreeNode>() : leftRoot.children;
+    List<TreeInfo.TreeNode> rightList = rightRoot == null ? new ArrayList<TreeInfo.TreeNode>() : rightRoot.children;
+
+    if (leftRoot == null && rightRoot == null) {
+      System.out.println(String.format("Path %s is neither found in left tree nor right tree.", path));
+    } else {
+      compareNodes(leftList, rightList, byteThreshold, nodeThreshold, debug, interactive);
+    }
+  }
+
+  /**
+   * Compare left tree and right tree at the same depth.
+   * @param left the left data tree
+   * @param right the right data tree
+   * @param depth the depth of the data tree to be compared at
+   * @param byteThreshold the node data delta size threshold, in bytes, for printing the node
+   * @param nodeThreshold the descendant node delta size threshold, in nodes, for printing the node
+   * @param debug If true, print more detailed debug information
+   * @param interactive If true, enter interactive mode
+   */
+  private static void compareLine(TreeInfo left, TreeInfo right, int depth, int byteThreshold, int nodeThreshold, boolean debug, boolean interactive) {
+    List<TreeInfo.TreeNode> leftList = depth >= left.nodesAtDepths.size() ? new ArrayList<>() : left.nodesAtDepths.get(depth);
+    List<TreeInfo.TreeNode> rightList = depth >= right.nodesAtDepths.size() ? new ArrayList<>() : right.nodesAtDepths.get(depth);
+
+    compareNodes(leftList, rightList, byteThreshold, nodeThreshold, debug, interactive);
+  }
+
+  private static void compareNodes(List<TreeInfo.TreeNode> leftList, List<TreeInfo.TreeNode> rightList, int byteThreshold, int nodeThreshold, boolean debug, boolean interactive) {
+    Comparator<TreeInfo.TreeNode> alphabeticComparator = TreeInfo.MakeAlphabeticComparator();
+    Collections.sort(leftList, alphabeticComparator);
+    Collections.sort(rightList, alphabeticComparator);
+
+    int leftIndex = 0;
+    int rightIndex = 0;
+
+    boolean leftRemaining = leftList.size() > leftIndex;
+    boolean rightRemaining = rightList.size() > rightIndex;
+    while (leftRemaining || rightRemaining) {
+      TreeInfo.TreeNode leftNode = null;
+      if (leftRemaining) {
+        leftNode = leftList.get(leftIndex);
+      }
+
+      TreeInfo.TreeNode rightNode = null;
+      if (rightRemaining) {
+        rightNode = rightList.get(rightIndex);
+      }
+
+      if (leftNode != null && rightNode != null) {
+        if (debug) {
+          System.out.println(String.format("Comparing %s to %s", leftNode.label, rightNode.label));
+        }
+        int result = leftNode.label.compareTo(rightNode.label);
+        if (result < 0) {
+          if (debug) {
+            System.out.println("left is less");
+          }
+          printLeftOnly(leftNode, byteThreshold, nodeThreshold, debug, interactive);
+          leftIndex++;
+        } else if (result > 0) {
+          if (debug) {
+            System.out.println("right is less");
+          }
+          printRightOnly(rightNode, byteThreshold, nodeThreshold, debug, interactive);
+          rightIndex++;
+        } else {
+          if (debug) {
+            System.out.println("same");
+          }
+          printBoth(leftNode, rightNode, byteThreshold, nodeThreshold, debug, interactive);
+          leftIndex++;
+          rightIndex++;
+        }
+      } else if (leftNode != null) {
+        printLeftOnly(leftNode, byteThreshold, nodeThreshold, debug, interactive);
+        leftIndex++;
+      } else {
+        printRightOnly(rightNode, byteThreshold, nodeThreshold, debug, interactive);
+        rightIndex++;
+      }
+
+      leftRemaining = leftList.size() > leftIndex;
+      rightRemaining = rightList.size() > rightIndex;
+    }
+  }
+
+  static void printLeftOnly(TreeInfo.TreeNode node, int byteThreshold, int nodeThreshold, boolean debug, boolean interactive) {
+    if (node.descendantSize > byteThreshold || node.descendantCount > nodeThreshold) {
+      StringBuilder builder = new StringBuilder();
+      builder.append(String.format("Node %s found only in left tree. ", node.label));
+      printNode(node, builder);
+      System.out.println(builder.toString());
+    } else if (debug || interactive) {
+      System.out.println(String.format("Filtered left node %s of size %d", node.label, node.descendantSize));
+    }
+  }
+
+  static void printRightOnly(TreeInfo.TreeNode node, int byteThreshold, int nodeThreshold, boolean debug, boolean interactive) {
+    if (node.descendantSize > byteThreshold || node.descendantCount > nodeThreshold) {
+      StringBuilder builder = new StringBuilder();
+      builder.append(String.format("Node %s found only in right tree. ", node.label));
+      printNode(node, builder);
+      System.out.println(builder.toString());
+    } else if (debug || interactive) {
+      System.out.println(String.format("Filtered right node %s of size %d", node.label, node.descendantSize));
+    }
+  }
+
+  static void printBoth(TreeInfo.TreeNode leftNode, TreeInfo.TreeNode rightNode, int byteThreshold, int nodeThreshold, boolean debug, boolean interactive) {
+    if (Math.abs(rightNode.descendantSize - leftNode.descendantSize) > byteThreshold
+        || Math.abs(rightNode.descendantCount - leftNode.descendantCount) > nodeThreshold) {
+      System.out.println(String.format(
+          "Node %s found in both trees. Delta: %d bytes, %d descendants",
+          leftNode.label,
+          rightNode.descendantSize - leftNode.descendantSize,
+          rightNode.descendantCount - leftNode.descendantCount));
+    } else if (debug || interactive) {
+      System.out.println(String.format("Filtered node %s of left size %d, right size %d", leftNode.label, leftNode.descendantSize, rightNode.descendantSize));
+    }
+  }
+
+  static void printNode(TreeInfo.TreeNode node, StringBuilder builder) {
+    builder.append(String.format("Descendant size: %d. Descendant count: %d", node.descendantSize, node.descendantCount));
+  }
+}