001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.zookeeper;
019
020import java.io.IOException;
021import java.util.concurrent.TimeUnit;
022import org.apache.hadoop.hbase.ZooKeeperConnectionException;
023import org.apache.hadoop.hbase.util.Threads;
024import org.apache.yetus.audience.InterfaceAudience;
025import org.apache.zookeeper.ZooKeeper;
026
027import org.apache.hbase.thirdparty.com.google.common.base.Stopwatch;
028
029/**
030 * Methods that help working with ZooKeeper
031 */
032@InterfaceAudience.Private
033public final class ZooKeeperHelper {
034  // This class cannot be instantiated
035  private ZooKeeperHelper() {
036  }
037
038  /**
039   * Get a ZooKeeper instance and wait until it connected before returning.
040   * @param sessionTimeoutMs Used as session timeout passed to the created ZooKeeper AND as the
041   *                         timeout to wait on connection establishment.
042   */
043  public static ZooKeeper getConnectedZooKeeper(String connectString, int sessionTimeoutMs)
044    throws IOException {
045    ZooKeeper zookeeper = new ZooKeeper(connectString, sessionTimeoutMs, e -> {
046    });
047    return ensureConnectedZooKeeper(zookeeper, sessionTimeoutMs);
048  }
049
050  /**
051   * Ensure passed zookeeper is connected.
052   * @param timeout Time to wait on established Connection
053   */
054  public static ZooKeeper ensureConnectedZooKeeper(ZooKeeper zookeeper, int timeout)
055    throws ZooKeeperConnectionException {
056    if (zookeeper.getState().isConnected()) {
057      return zookeeper;
058    }
059    Stopwatch stopWatch = Stopwatch.createStarted();
060    // Make sure we are connected before we hand it back.
061    while (!zookeeper.getState().isConnected()) {
062      Threads.sleep(1);
063      if (stopWatch.elapsed(TimeUnit.MILLISECONDS) > timeout) {
064        throw new ZooKeeperConnectionException("Failed connect after waiting "
065          + stopWatch.elapsed(TimeUnit.MILLISECONDS) + "ms (zk session timeout); " + zookeeper);
066      }
067    }
068    return zookeeper;
069  }
070}