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;
022
023import org.apache.hadoop.hbase.ZooKeeperConnectionException;
024import org.apache.hadoop.hbase.util.Threads;
025import org.apache.hbase.thirdparty.com.google.common.base.Stopwatch;
026import org.apache.yetus.audience.InterfaceAudience;
027import org.apache.zookeeper.ZooKeeper;
028
029
030/**
031 * Methods that help working with ZooKeeper
032 */
033@InterfaceAudience.Private
034public final class ZooKeeperHelper {
035  // This class cannot be instantiated
036  private ZooKeeperHelper() {
037  }
038
039  /**
040   * Get a ZooKeeper instance and wait until it connected before returning.
041   * @param sessionTimeoutMs Used as session timeout passed to the created ZooKeeper AND as the
042   *   timeout to wait on connection establishment.
043   */
044  public static ZooKeeper getConnectedZooKeeper(String connectString, int sessionTimeoutMs)
045      throws IOException {
046    ZooKeeper zookeeper = new ZooKeeper(connectString, sessionTimeoutMs, e -> {});
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); " +
066            zookeeper);
067      }
068    }
069    return zookeeper;
070  }
071}