diff --git a/zookeeper-docs/src/main/resources/markdown/zookeeperCLI.md b/zookeeper-docs/src/main/resources/markdown/zookeeperCLI.md index 668e64e8ba8..7096aa0cc89 100644 --- a/zookeeper-docs/src/main/resources/markdown/zookeeperCLI.md +++ b/zookeeper-docs/src/main/resources/markdown/zookeeperCLI.md @@ -24,6 +24,8 @@ Enter into the ZooKeeper-cli bin/zkCli.sh # connect to the remote host with timeout:3s bin/zkCli.sh -timeout 3000 -server remoteIP:2181 +# connect to the remote host with -waitforconnection option to wait for connection success before executing commands +bin/zkCli.sh -waitforconnection -timeout 3000 -server remoteIP:2181 # connect with a custom client configuration properties file bin/zkCli.sh -client-configuration /path/to/client.properties ``` diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeperMain.java b/zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeperMain.java index 9c7dd0ba2ec..4ee378fac05 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeperMain.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeperMain.java @@ -112,7 +112,7 @@ public void process(WatchedEvent event) { if (connectLatch != null) { // connection success if (event.getType() == Event.EventType.None - && event.getState() == Event.KeeperState.SyncConnected) { + && event.getState() == Event.KeeperState.SyncConnected) { connectLatch.countDown(); } } @@ -261,17 +261,6 @@ protected void connectToZK(String newHost) throws InterruptedException, IOExcept System.setProperty(ZKClientConfig.SECURE_CLIENT, "true"); System.out.println("Secure connection is enabled"); } - if (cl.getOption("waitforconnection") != null) { - connectLatch = new CountDownLatch(1); - } - int timeout = Integer.parseInt(cl.getOption("timeout")); - zk = new ZooKeeperAdmin(host, timeout, new MyWatcher(), readOnly); - if (connectLatch != null) { - if (!connectLatch.await(timeout, TimeUnit.MILLISECONDS)) { - zk.close(); - throw new IOException(KeeperException.create(KeeperException.Code.CONNECTIONLOSS)); - } - } ZKClientConfig clientConfig = null; @@ -284,7 +273,19 @@ protected void connectToZK(String newHost) throws InterruptedException, IOExcept } } - zk = new ZooKeeperAdmin(host, Integer.parseInt(cl.getOption("timeout")), new MyWatcher(), readOnly, clientConfig); + if (cl.getOption("waitforconnection") != null) { + connectLatch = new CountDownLatch(1); + } + + int timeout = Integer.parseInt(cl.getOption("timeout")); + zk = new ZooKeeperAdmin(host, timeout, new MyWatcher(), readOnly, clientConfig); + if (connectLatch != null) { + if (!connectLatch.await(timeout, TimeUnit.MILLISECONDS)) { + zk.close(); + throw new IOException(KeeperException.create(KeeperException.Code.CONNECTIONLOSS)); + } + } + } public static void main(String[] args) throws IOException, InterruptedException {