Przeglądaj źródła

ZOOKEEPER-4473: zooInspector root child creates fail with path validate fix

zooInspector root child creates fail with path validate fix.
create node update UI only if creation success, if fail show message dialog about the reason.
add basic ZooInspectorManagerImpl tests using mocked zookeeper client.

Author: 67 <67@gd67.com>

Reviewers: Enrico Olivelli <eolivelli@apache.org>, Mate Szalay-Beko <symat@apache.org>

Closes #1818 from iamgd67/ZOOKEEPER-4473
67 3 lat temu
rodzic
commit
99cb20e827

+ 6 - 0
zookeeper-contrib/zookeeper-contrib-zooinspector/pom.xml

@@ -114,5 +114,11 @@
       <artifactId>apache-rat-tasks</artifactId>
       <artifactId>apache-rat-tasks</artifactId>
       <version>${rat.version}</version>
       <version>${rat.version}</version>
     </dependency>
     </dependency>
+
+    <dependency>
+      <groupId>org.mockito</groupId>
+      <artifactId>mockito-core</artifactId>
+      <scope>test</scope>
+    </dependency>
   </dependencies>
   </dependencies>
 </project>
 </project>

+ 28 - 8
zookeeper-contrib/zookeeper-contrib-zooinspector/src/main/java/org/apache/zookeeper/inspector/gui/ZooInspectorTreeView.java

@@ -19,6 +19,7 @@ package org.apache.zookeeper.inspector.gui;
 
 
 import com.nitido.utils.toaster.Toaster;
 import com.nitido.utils.toaster.Toaster;
 import org.apache.zookeeper.inspector.gui.nodeviewer.NodeSelectionListener;
 import org.apache.zookeeper.inspector.gui.nodeviewer.NodeSelectionListener;
+import org.apache.zookeeper.inspector.logger.LoggerFactory;
 import org.apache.zookeeper.inspector.manager.NodeListener;
 import org.apache.zookeeper.inspector.manager.NodeListener;
 import org.apache.zookeeper.inspector.manager.Pair;
 import org.apache.zookeeper.inspector.manager.Pair;
 import org.apache.zookeeper.inspector.manager.ZooInspectorManager;
 import org.apache.zookeeper.inspector.manager.ZooInspectorManager;
@@ -355,6 +356,12 @@ public class ZooInspectorTreeView extends JPanel {
         return selected != null ? ((ZooInspectorTreeNode) selected.getLastPathComponent()) : null;
         return selected != null ? ((ZooInspectorTreeNode) selected.getLastPathComponent()) : null;
     }
     }
 
 
+    private void showWarnDialog(String message){
+        JOptionPane.showMessageDialog(this,
+                message, "Error",
+                JOptionPane.ERROR_MESSAGE);
+    }
+
     ///////////////////////////////// BACKING DATA MODEL /////////////////////////////////
     ///////////////////////////////// BACKING DATA MODEL /////////////////////////////////
 
 
     /**
     /**
@@ -386,17 +393,30 @@ public class ZooInspectorTreeView extends JPanel {
                 @Override
                 @Override
                 protected void done() {
                 protected void done() {
                     //runs on the UI event thread
                     //runs on the UI event thread
+                    boolean success;
+                    try {
+                        success = get();
+                    } catch (Exception e) {
+                        success = false;
+                        LoggerFactory.getLogger().error("create fail for {} {}", parentNode, newNodeName, e);
+                        showWarnDialog("create " + newNodeName + " in " + parentNode + " fail, exception is " + e.getMessage());
+                    }
 
 
-                    //extra logic to find the correct spot alphabetically to insert the new node in the tree`
-                    int i = 0;
-                    for (; i < parentNode.getChildCount(); i++) {
-                        ZooInspectorTreeNode existingChild = (ZooInspectorTreeNode) parentNode.getChildAt(i);
-                        if (newNodeName.compareTo(existingChild.getName()) < 0) {
-                            break;
+                    if (!success) {
+                        showWarnDialog("create " + newNodeName + " in " + parentNode + " fail, see log for more detail");
+                    }
+                    else {
+                        //extra logic to find the correct spot alphabetically to insert the new node in the tree`
+                        int i = 0;
+                        for (; i < parentNode.getChildCount(); i++) {
+                            ZooInspectorTreeNode existingChild = (ZooInspectorTreeNode) parentNode.getChildAt(i);
+                            if (newNodeName.compareTo(existingChild.getName()) < 0) {
+                                break;
+                            }
                         }
                         }
+                        insertNodeInto(new ZooInspectorTreeNode(newNodeName, parentNode, 0), parentNode, i);
+                        parentNode.setNumDisplayChildren(parentNode.getNumDisplayChildren() + 1);
                     }
                     }
-                    insertNodeInto(new ZooInspectorTreeNode(newNodeName, parentNode, 0), parentNode, i);
-                    parentNode.setNumDisplayChildren(parentNode.getNumDisplayChildren() + 1);
                     getRootPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                     getRootPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                 }
                 }
             };
             };

+ 13 - 3
zookeeper-contrib/zookeeper-contrib-zooinspector/src/main/java/org/apache/zookeeper/inspector/manager/ZooInspectorManagerImpl.java

@@ -106,10 +106,13 @@ public class ZooInspectorManagerImpl implements ZooInspectorManager {
     private static final File defaultConnectionFile = new File(
     private static final File defaultConnectionFile = new File(
             "./src/main/resources/defaultConnectionSettings.cfg");
             "./src/main/resources/defaultConnectionSettings.cfg");
 
 
-    private DataEncryptionManager encryptionManager;
+    //package visible for test
+    DataEncryptionManager encryptionManager;
     private String connectString;
     private String connectString;
     private int sessionTimeout;
     private int sessionTimeout;
-    private ZooKeeper zooKeeper;
+
+    //package visible for test
+    ZooKeeper zooKeeper;
     private final Map<String, NodeWatcher> watchers = new HashMap<String, NodeWatcher>();
     private final Map<String, NodeWatcher> watchers = new HashMap<String, NodeWatcher>();
     protected boolean connected = true;
     protected boolean connected = true;
     private Properties lastConnectionProps;
     private Properties lastConnectionProps;
@@ -390,7 +393,14 @@ public class ZooInspectorManagerImpl implements ZooInspectorManager {
             try {
             try {
                 String[] nodeElements = nodeName.split("/");
                 String[] nodeElements = nodeName.split("/");
                 for (String nodeElement : nodeElements) {
                 for (String nodeElement : nodeElements) {
-                    String node = parent + "/" + nodeElement;
+                    String node;
+                    //for case parent is "/" and maybe other cases
+                    if (parent.endsWith("/")) {
+                        node = parent + nodeElement;
+                    }
+                    else {
+                        node = parent + "/" + nodeElement;
+                    }
                     Stat s = zooKeeper.exists(node, false);
                     Stat s = zooKeeper.exists(node, false);
                     if (s == null) {
                     if (s == null) {
                         zooKeeper.create(node, this.encryptionManager
                         zooKeeper.create(node, this.encryptionManager

+ 113 - 0
zookeeper-contrib/zookeeper-contrib-zooinspector/src/test/java/org/apache/zookeeper/inspector/manager/ZooInspectorManagerImplTest.java

@@ -0,0 +1,113 @@
+/**
+ * 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.inspector.manager;
+
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.common.PathUtils;
+import org.apache.zookeeper.data.Stat;
+import org.apache.zookeeper.inspector.encryption.BasicDataEncryptionManager;
+import org.apache.zookeeper.retry.ZooKeeperRetry;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.io.IOException;
+
+public class ZooInspectorManagerImplTest {
+
+    /**
+     * test create zookeeper node operation,
+     * no easy way to create a real zk server so use a mocked client that only validate path
+     *
+     * @throws IOException
+     * @throws KeeperException
+     * @throws InterruptedException
+     */
+    @Test
+    public void testNodeCreateRoot() throws IOException, KeeperException, InterruptedException {
+        ZooKeeper mockedZk = getMockedZk();
+
+        ZooInspectorManagerImpl manager = getInspectorManagerImpl(mockedZk);
+
+        boolean createSuccess = manager.createNode("/", "test");
+        Assert.assertTrue(createSuccess);
+    }
+
+    /**
+     * test create a normal child node
+     *
+     * @throws IOException
+     * @throws KeeperException
+     * @throws InterruptedException
+     */
+
+    @Test
+    public void testNodeCreateNormal() throws IOException, KeeperException, InterruptedException {
+        ZooKeeper mockedZk = getMockedZk();
+
+        ZooInspectorManagerImpl manager = getInspectorManagerImpl(mockedZk);
+
+        boolean createSuccess = manager.createNode("/parent", "test");
+        Assert.assertTrue(createSuccess);
+    }
+
+
+    /**
+     * create a mocked zk client only check path validate
+     *
+     * @return
+     * @throws KeeperException
+     * @throws InterruptedException
+     */
+    private ZooKeeper getMockedZk() throws KeeperException, InterruptedException {
+        ZooKeeper mockZk = Mockito.mock(ZooKeeperRetry.class);
+        Mockito.when(mockZk.exists(Mockito.anyString(), Mockito.anyBoolean())).then((Answer<Stat>) invocation -> {
+            String path = invocation.getArgument(0);
+            PathUtils.validatePath(path);
+            return null;
+        });
+        Mockito.when(mockZk.create(Mockito.anyString(), Mockito.any(), Mockito.any(),
+                Mockito.any())).then(new Answer<String>() {
+            @Override
+            public String answer(InvocationOnMock invocation) throws Throwable {
+                String path = invocation.getArgument(0);
+                PathUtils.validatePath(path);
+                return path;
+            }
+        });
+        return mockZk;
+    }
+
+    /**
+     * create a inspector manager instance from zk
+     *
+     * @param zooKeeper
+     * @return
+     * @throws IOException
+     */
+    private ZooInspectorManagerImpl getInspectorManagerImpl(ZooKeeper zooKeeper) throws IOException {
+        ZooInspectorManagerImpl manager = new ZooInspectorManagerImpl();
+        manager.zooKeeper = zooKeeper;
+        manager.connected = true;
+        manager.encryptionManager = new BasicDataEncryptionManager();
+        return manager;
+    }
+}