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.quotas;
019
020import java.io.IOException;
021import org.apache.hadoop.conf.Configuration;
022import org.apache.hadoop.hbase.util.Bytes;
023import org.apache.hadoop.hbase.zookeeper.ZKUtil;
024import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
025import org.apache.hadoop.hbase.zookeeper.ZNodePaths;
026import org.apache.yetus.audience.InterfaceAudience;
027import org.apache.zookeeper.KeeperException;
028
029/**
030 * ZK based rpc throttle storage.
031 */
032@InterfaceAudience.Private
033public class RpcThrottleStorage {
034  public static final String RPC_THROTTLE_ZNODE = "zookeeper.znode.quota.rpc.throttle";
035  public static final String RPC_THROTTLE_ZNODE_DEFAULT = "rpc-throttle";
036
037  private final ZKWatcher zookeeper;
038  private final String rpcThrottleZNode;
039
040  public RpcThrottleStorage(ZKWatcher zookeeper, Configuration conf) {
041    this.zookeeper = zookeeper;
042    this.rpcThrottleZNode = ZNodePaths.joinZNode(zookeeper.getZNodePaths().baseZNode,
043      conf.get(RPC_THROTTLE_ZNODE, RPC_THROTTLE_ZNODE_DEFAULT));
044  }
045
046  public boolean isRpcThrottleEnabled() throws IOException {
047    try {
048      byte[] upData = ZKUtil.getData(zookeeper, rpcThrottleZNode);
049      return upData == null || Bytes.toBoolean(upData);
050    } catch (KeeperException | InterruptedException e) {
051      throw new IOException("Failed to get rpc throttle", e);
052    }
053  }
054
055  /**
056   * Store the rpc throttle value.
057   * @param enable Set to <code>true</code> to enable, <code>false</code> to disable.
058   * @throws IOException if an unexpected io exception occurs
059   */
060  public void switchRpcThrottle(boolean enable) throws IOException {
061    try {
062      byte[] upData = Bytes.toBytes(enable);
063      ZKUtil.createSetData(zookeeper, rpcThrottleZNode, upData);
064    } catch (KeeperException e) {
065      throw new IOException("Failed to store rpc throttle", e);
066    }
067  }
068}