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.util.Collections;
021import java.util.List;
022import java.util.stream.Collectors;
023import org.apache.hadoop.hbase.Abortable;
024import org.apache.hadoop.hbase.ServerName;
025import org.apache.yetus.audience.InterfaceAudience;
026import org.apache.zookeeper.KeeperException;
027import org.slf4j.Logger;
028import org.slf4j.LoggerFactory;
029
030import org.apache.hbase.thirdparty.org.apache.commons.collections4.CollectionUtils;
031
032/**
033 * Class for tracking the region servers for a cluster.
034 */
035@InterfaceAudience.Private
036public class RegionServerAddressTracker extends ZKListener {
037
038  private static final Logger LOG = LoggerFactory.getLogger(RegionServerAddressTracker.class);
039
040  private volatile List<ServerName> regionServers = Collections.emptyList();
041
042  private final Abortable abortable;
043
044  public RegionServerAddressTracker(ZKWatcher watcher, Abortable abortable) {
045    super(watcher);
046    this.abortable = abortable;
047    watcher.registerListener(this);
048    loadRegionServerList();
049  }
050
051  private void loadRegionServerList() {
052    List<String> names;
053    try {
054      names = ZKUtil.listChildrenAndWatchForNewChildren(watcher, watcher.getZNodePaths().rsZNode);
055    } catch (KeeperException e) {
056      LOG.error("failed to list region servers", e);
057      abortable.abort("failed to list region servers", e);
058      return;
059    }
060    if (CollectionUtils.isEmpty(names)) {
061      regionServers = Collections.emptyList();
062    } else {
063      regionServers = names.stream().map(ServerName::parseServerName)
064        .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
065    }
066  }
067
068  @Override
069  public void nodeChildrenChanged(String path) {
070    if (path.equals(watcher.getZNodePaths().rsZNode)) {
071      loadRegionServerList();
072    }
073  }
074
075  public List<ServerName> getRegionServers() {
076    return regionServers;
077  }
078}