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 java.util.List;
022import java.util.Optional;
023import org.apache.hadoop.hbase.TableName;
024import org.apache.hadoop.hbase.client.TableDescriptor;
025import org.apache.hadoop.hbase.ipc.RpcScheduler;
026import org.apache.hadoop.hbase.ipc.RpcServer;
027import org.apache.hadoop.hbase.regionserver.Region;
028import org.apache.hadoop.hbase.regionserver.RegionServerServices;
029import org.apache.hadoop.hbase.security.User;
030import org.apache.hadoop.security.UserGroupInformation;
031import org.apache.yetus.audience.InterfaceAudience;
032import org.apache.yetus.audience.InterfaceStability;
033import org.slf4j.Logger;
034import org.slf4j.LoggerFactory;
035
036import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos;
037
038/**
039 * Region Server Quota Manager. It is responsible to provide access to the quota information of each
040 * user/table. The direct user of this class is the RegionServer that will get and check the
041 * user/table quota for each operation (put, get, scan). For system tables and user/table with a
042 * quota specified, the quota check will be a noop.
043 */
044@InterfaceAudience.Private
045@InterfaceStability.Evolving
046public class RegionServerRpcQuotaManager implements RpcQuotaManager {
047  private static final Logger LOG = LoggerFactory.getLogger(RegionServerRpcQuotaManager.class);
048
049  private final RegionServerServices rsServices;
050
051  private QuotaCache quotaCache = null;
052  private volatile boolean rpcThrottleEnabled;
053  // Storage for quota rpc throttle
054  private RpcThrottleStorage rpcThrottleStorage;
055
056  public RegionServerRpcQuotaManager(final RegionServerServices rsServices) {
057    this.rsServices = rsServices;
058    rpcThrottleStorage =
059      new RpcThrottleStorage(rsServices.getZooKeeper(), rsServices.getConfiguration());
060  }
061
062  public void start(final RpcScheduler rpcScheduler) throws IOException {
063    if (!QuotaUtil.isQuotaEnabled(rsServices.getConfiguration())) {
064      LOG.info("Quota support disabled");
065      return;
066    }
067
068    LOG.info("Initializing RPC quota support");
069
070    // Initialize quota cache
071    quotaCache = new QuotaCache(rsServices);
072    quotaCache.start();
073    rpcThrottleEnabled = rpcThrottleStorage.isRpcThrottleEnabled();
074    LOG.info("Start rpc quota manager and rpc throttle enabled is {}", rpcThrottleEnabled);
075  }
076
077  public void stop() {
078    if (isQuotaEnabled()) {
079      quotaCache.stop("shutdown");
080    }
081  }
082
083  protected boolean isRpcThrottleEnabled() {
084    return rpcThrottleEnabled;
085  }
086
087  private boolean isQuotaEnabled() {
088    return quotaCache != null;
089  }
090
091  public void switchRpcThrottle(boolean enable) throws IOException {
092    if (isQuotaEnabled()) {
093      if (rpcThrottleEnabled != enable) {
094        boolean previousEnabled = rpcThrottleEnabled;
095        rpcThrottleEnabled = rpcThrottleStorage.isRpcThrottleEnabled();
096        LOG.info("Switch rpc throttle from {} to {}", previousEnabled, rpcThrottleEnabled);
097      } else {
098        LOG.warn(
099          "Skip switch rpc throttle because previous value {} is the same as current value {}",
100          rpcThrottleEnabled, enable);
101      }
102    } else {
103      LOG.warn("Skip switch rpc throttle to {} because rpc quota is disabled", enable);
104    }
105  }
106
107  QuotaCache getQuotaCache() {
108    return quotaCache;
109  }
110
111  /**
112   * Returns the quota for an operation.
113   * @param ugi   the user that is executing the operation
114   * @param table the table where the operation will be executed
115   * @return the OperationQuota
116   */
117  public OperationQuota getQuota(final UserGroupInformation ugi, final TableName table,
118    final int blockSizeBytes) {
119    if (isQuotaEnabled() && !table.isSystemTable() && isRpcThrottleEnabled()) {
120      UserQuotaState userQuotaState = quotaCache.getUserQuotaState(ugi);
121      QuotaLimiter userLimiter = userQuotaState.getTableLimiter(table);
122      boolean useNoop = userLimiter.isBypass();
123      if (userQuotaState.hasBypassGlobals()) {
124        if (LOG.isTraceEnabled()) {
125          LOG.trace("get quota for ugi=" + ugi + " table=" + table + " userLimiter=" + userLimiter);
126        }
127        if (!useNoop) {
128          return new DefaultOperationQuota(this.rsServices.getConfiguration(), blockSizeBytes,
129            userLimiter);
130        }
131      } else {
132        QuotaLimiter nsLimiter = quotaCache.getNamespaceLimiter(table.getNamespaceAsString());
133        QuotaLimiter tableLimiter = quotaCache.getTableLimiter(table);
134        QuotaLimiter rsLimiter =
135          quotaCache.getRegionServerQuotaLimiter(QuotaTableUtil.QUOTA_REGION_SERVER_ROW_KEY);
136        useNoop &= tableLimiter.isBypass() && nsLimiter.isBypass() && rsLimiter.isBypass();
137        boolean exceedThrottleQuotaEnabled = quotaCache.isExceedThrottleQuotaEnabled();
138        if (LOG.isTraceEnabled()) {
139          LOG.trace("get quota for ugi=" + ugi + " table=" + table + " userLimiter=" + userLimiter
140            + " tableLimiter=" + tableLimiter + " nsLimiter=" + nsLimiter + " rsLimiter="
141            + rsLimiter + " exceedThrottleQuotaEnabled=" + exceedThrottleQuotaEnabled);
142        }
143        if (!useNoop) {
144          if (exceedThrottleQuotaEnabled) {
145            return new ExceedOperationQuota(this.rsServices.getConfiguration(), blockSizeBytes,
146              rsLimiter, userLimiter, tableLimiter, nsLimiter);
147          } else {
148            return new DefaultOperationQuota(this.rsServices.getConfiguration(), blockSizeBytes,
149              userLimiter, tableLimiter, nsLimiter, rsLimiter);
150          }
151        }
152      }
153    }
154    return NoopOperationQuota.get();
155  }
156
157  @Override
158  public OperationQuota checkScanQuota(final Region region,
159    final ClientProtos.ScanRequest scanRequest, long maxScannerResultSize,
160    long maxBlockBytesScanned, long prevBlockBytesScannedDifference)
161    throws IOException, RpcThrottlingException {
162    Optional<User> user = RpcServer.getRequestUser();
163    UserGroupInformation ugi;
164    if (user.isPresent()) {
165      ugi = user.get().getUGI();
166    } else {
167      ugi = User.getCurrent().getUGI();
168    }
169    TableDescriptor tableDescriptor = region.getTableDescriptor();
170    TableName table = tableDescriptor.getTableName();
171
172    OperationQuota quota = getQuota(ugi, table, region.getMinBlockSizeBytes());
173    try {
174      quota.checkScanQuota(scanRequest, maxScannerResultSize, maxBlockBytesScanned,
175        prevBlockBytesScannedDifference);
176    } catch (RpcThrottlingException e) {
177      LOG.debug("Throttling exception for user=" + ugi.getUserName() + " table=" + table + " scan="
178        + scanRequest.getScannerId() + ": " + e.getMessage());
179      throw e;
180    }
181    return quota;
182  }
183
184  @Override
185  public OperationQuota checkBatchQuota(final Region region,
186    final OperationQuota.OperationType type) throws IOException, RpcThrottlingException {
187    switch (type) {
188      case GET:
189        return this.checkBatchQuota(region, 0, 1);
190      case MUTATE:
191        return this.checkBatchQuota(region, 1, 0);
192      case CHECK_AND_MUTATE:
193        return this.checkBatchQuota(region, 1, 1);
194    }
195    throw new RuntimeException("Invalid operation type: " + type);
196  }
197
198  @Override
199  public OperationQuota checkBatchQuota(final Region region,
200    final List<ClientProtos.Action> actions, boolean hasCondition)
201    throws IOException, RpcThrottlingException {
202    int numWrites = 0;
203    int numReads = 0;
204    for (final ClientProtos.Action action : actions) {
205      if (action.hasMutation()) {
206        numWrites++;
207        OperationQuota.OperationType operationType =
208          QuotaUtil.getQuotaOperationType(action, hasCondition);
209        if (operationType == OperationQuota.OperationType.CHECK_AND_MUTATE) {
210          numReads++;
211        }
212      } else if (action.hasGet()) {
213        numReads++;
214      }
215    }
216    return checkBatchQuota(region, numWrites, numReads);
217  }
218
219  /**
220   * Check the quota for the current (rpc-context) user. Returns the OperationQuota used to get the
221   * available quota and to report the data/usage of the operation.
222   * @param region    the region where the operation will be performed
223   * @param numWrites number of writes to perform
224   * @param numReads  number of short-reads to perform
225   * @return the OperationQuota
226   * @throws RpcThrottlingException if the operation cannot be executed due to quota exceeded.
227   */
228  @Override
229  public OperationQuota checkBatchQuota(final Region region, final int numWrites,
230    final int numReads) throws IOException, RpcThrottlingException {
231    Optional<User> user = RpcServer.getRequestUser();
232    UserGroupInformation ugi;
233    if (user.isPresent()) {
234      ugi = user.get().getUGI();
235    } else {
236      ugi = User.getCurrent().getUGI();
237    }
238    TableDescriptor tableDescriptor = region.getTableDescriptor();
239    TableName table = tableDescriptor.getTableName();
240
241    OperationQuota quota = getQuota(ugi, table, region.getMinBlockSizeBytes());
242    try {
243      quota.checkBatchQuota(numWrites, numReads);
244    } catch (RpcThrottlingException e) {
245      LOG.debug("Throttling exception for user=" + ugi.getUserName() + " table=" + table
246        + " numWrites=" + numWrites + " numReads=" + numReads + ": " + e.getMessage());
247      throw e;
248    }
249    return quota;
250  }
251}