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 */
018
019package org.apache.hadoop.hbase.ipc;
020
021import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION;
022
023import java.io.IOException;
024import java.net.InetAddress;
025import java.net.InetSocketAddress;
026import java.nio.ByteBuffer;
027import java.nio.channels.ReadableByteChannel;
028import java.nio.channels.WritableByteChannel;
029import java.util.ArrayList;
030import java.util.Collections;
031import java.util.HashMap;
032import java.util.List;
033import java.util.Locale;
034import java.util.Map;
035import java.util.Optional;
036import java.util.concurrent.atomic.LongAdder;
037
038import org.apache.hadoop.conf.Configuration;
039import org.apache.hadoop.hbase.CallQueueTooBigException;
040import org.apache.hadoop.hbase.CellScanner;
041import org.apache.hadoop.hbase.DoNotRetryIOException;
042import org.apache.hadoop.hbase.HConstants;
043import org.apache.hadoop.hbase.Server;
044import org.apache.hadoop.hbase.conf.ConfigurationObserver;
045import org.apache.hadoop.hbase.exceptions.RequestTooBigException;
046import org.apache.hadoop.hbase.io.ByteBufferPool;
047import org.apache.hadoop.hbase.monitoring.MonitoredRPCHandler;
048import org.apache.hadoop.hbase.monitoring.TaskMonitor;
049import org.apache.hadoop.hbase.nio.ByteBuff;
050import org.apache.hadoop.hbase.nio.MultiByteBuff;
051import org.apache.hadoop.hbase.nio.SingleByteBuff;
052import org.apache.hadoop.hbase.regionserver.RSRpcServices;
053import org.apache.hadoop.hbase.security.SaslUtil;
054import org.apache.hadoop.hbase.security.SaslUtil.QualityOfProtection;
055import org.apache.hadoop.hbase.security.User;
056import org.apache.hadoop.hbase.security.UserProvider;
057import org.apache.hadoop.hbase.security.token.AuthenticationTokenSecretManager;
058import org.apache.hadoop.hbase.util.Pair;
059import org.apache.hadoop.security.UserGroupInformation;
060import org.apache.hadoop.security.authorize.AuthorizationException;
061import org.apache.hadoop.security.authorize.PolicyProvider;
062import org.apache.hadoop.security.authorize.ServiceAuthorizationManager;
063import org.apache.hadoop.security.token.SecretManager;
064import org.apache.hadoop.security.token.TokenIdentifier;
065import org.apache.yetus.audience.InterfaceAudience;
066import org.slf4j.Logger;
067import org.slf4j.LoggerFactory;
068
069import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
070import org.apache.hbase.thirdparty.com.google.protobuf.BlockingService;
071import org.apache.hbase.thirdparty.com.google.protobuf.Descriptors.MethodDescriptor;
072import org.apache.hbase.thirdparty.com.google.protobuf.Message;
073import org.apache.hbase.thirdparty.com.google.protobuf.ServiceException;
074import org.apache.hbase.thirdparty.com.google.protobuf.TextFormat;
075import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
076import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos;
077import org.apache.hadoop.hbase.shaded.protobuf.generated.RPCProtos.ConnectionHeader;
078
079import com.fasterxml.jackson.databind.ObjectMapper;
080
081/**
082 * An RPC server that hosts protobuf described Services.
083 *
084 */
085@InterfaceAudience.Private
086public abstract class RpcServer implements RpcServerInterface,
087    ConfigurationObserver {
088  // LOG is being used in CallRunner and the log level is being changed in tests
089  public static final Logger LOG = LoggerFactory.getLogger(RpcServer.class);
090  protected static final CallQueueTooBigException CALL_QUEUE_TOO_BIG_EXCEPTION
091      = new CallQueueTooBigException();
092
093  private final boolean authorize;
094  protected boolean isSecurityEnabled;
095
096  public static final byte CURRENT_VERSION = 0;
097
098  /**
099   * Whether we allow a fallback to SIMPLE auth for insecure clients when security is enabled.
100   */
101  public static final String FALLBACK_TO_INSECURE_CLIENT_AUTH =
102          "hbase.ipc.server.fallback-to-simple-auth-allowed";
103
104  /**
105   * How many calls/handler are allowed in the queue.
106   */
107  protected static final int DEFAULT_MAX_CALLQUEUE_LENGTH_PER_HANDLER = 10;
108
109  protected final CellBlockBuilder cellBlockBuilder;
110
111  protected static final String AUTH_FAILED_FOR = "Auth failed for ";
112  protected static final String AUTH_SUCCESSFUL_FOR = "Auth successful for ";
113  protected static final Logger AUDITLOG = LoggerFactory.getLogger("SecurityLogger."
114      + Server.class.getName());
115  protected SecretManager<TokenIdentifier> secretManager;
116  protected final Map<String, String> saslProps;
117
118  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="IS2_INCONSISTENT_SYNC",
119      justification="Start is synchronized so authManager creation is single-threaded")
120  protected ServiceAuthorizationManager authManager;
121
122  /** This is set to Call object before Handler invokes an RPC and ybdie
123   * after the call returns.
124   */
125  protected static final ThreadLocal<RpcCall> CurCall = new ThreadLocal<>();
126
127  /** Keeps MonitoredRPCHandler per handler thread. */
128  protected static final ThreadLocal<MonitoredRPCHandler> MONITORED_RPC = new ThreadLocal<>();
129
130  protected final InetSocketAddress bindAddress;
131
132  protected MetricsHBaseServer metrics;
133
134  protected final Configuration conf;
135
136  /**
137   * Maximum size in bytes of the currently queued and running Calls. If a new Call puts us over
138   * this size, then we will reject the call (after parsing it though). It will go back to the
139   * client and client will retry. Set this size with "hbase.ipc.server.max.callqueue.size". The
140   * call queue size gets incremented after we parse a call and before we add it to the queue of
141   * calls for the scheduler to use. It get decremented after we have 'run' the Call. The current
142   * size is kept in {@link #callQueueSizeInBytes}.
143   * @see #callQueueSizeInBytes
144   * @see #DEFAULT_MAX_CALLQUEUE_SIZE
145   */
146  protected final long maxQueueSizeInBytes;
147  protected static final int DEFAULT_MAX_CALLQUEUE_SIZE = 1024 * 1024 * 1024;
148
149  /**
150   * This is a running count of the size in bytes of all outstanding calls whether currently
151   * executing or queued waiting to be run.
152   */
153  protected final LongAdder callQueueSizeInBytes = new LongAdder();
154
155  protected final boolean tcpNoDelay; // if T then disable Nagle's Algorithm
156  protected final boolean tcpKeepAlive; // if T then use keepalives
157
158  /**
159   * This flag is used to indicate to sub threads when they should go down.  When we call
160   * {@link #start()}, all threads started will consult this flag on whether they should
161   * keep going.  It is set to false when {@link #stop()} is called.
162   */
163  volatile boolean running = true;
164
165  /**
166   * This flag is set to true after all threads are up and 'running' and the server is then opened
167   * for business by the call to {@link #start()}.
168   */
169  volatile boolean started = false;
170
171  protected AuthenticationTokenSecretManager authTokenSecretMgr = null;
172
173  protected HBaseRPCErrorHandler errorHandler = null;
174
175  public static final String MAX_REQUEST_SIZE = "hbase.ipc.max.request.size";
176  protected static final RequestTooBigException REQUEST_TOO_BIG_EXCEPTION =
177      new RequestTooBigException();
178
179  protected static final String WARN_RESPONSE_TIME = "hbase.ipc.warn.response.time";
180  protected static final String WARN_RESPONSE_SIZE = "hbase.ipc.warn.response.size";
181
182  /**
183   * Minimum allowable timeout (in milliseconds) in rpc request's header. This
184   * configuration exists to prevent the rpc service regarding this request as timeout immediately.
185   */
186  protected static final String MIN_CLIENT_REQUEST_TIMEOUT = "hbase.ipc.min.client.request.timeout";
187  protected static final int DEFAULT_MIN_CLIENT_REQUEST_TIMEOUT = 20;
188
189  /** Default value for above params */
190  public static final int DEFAULT_MAX_REQUEST_SIZE = DEFAULT_MAX_CALLQUEUE_SIZE / 4; // 256M
191  protected static final int DEFAULT_WARN_RESPONSE_TIME = 10000; // milliseconds
192  protected static final int DEFAULT_WARN_RESPONSE_SIZE = 100 * 1024 * 1024;
193
194  protected static final ObjectMapper MAPPER = new ObjectMapper();
195
196  protected final int maxRequestSize;
197  protected final int warnResponseTime;
198  protected final int warnResponseSize;
199
200  protected final int minClientRequestTimeout;
201
202  protected final Server server;
203  protected final List<BlockingServiceAndInterface> services;
204
205  protected final RpcScheduler scheduler;
206
207  protected UserProvider userProvider;
208
209  protected final ByteBufferPool reservoir;
210  // The requests and response will use buffers from ByteBufferPool, when the size of the
211  // request/response is at least this size.
212  // We make this to be 1/6th of the pool buffer size.
213  protected final int minSizeForReservoirUse;
214
215  protected volatile boolean allowFallbackToSimpleAuth;
216
217  /**
218   * Used to get details for scan with a scanner_id<br/>
219   * TODO try to figure out a better way and remove reference from regionserver package later.
220   */
221  private RSRpcServices rsRpcServices;
222
223  @FunctionalInterface
224  protected static interface CallCleanup {
225    void run();
226  }
227
228  /**
229   * Datastructure for passing a {@link BlockingService} and its associated class of
230   * protobuf service interface.  For example, a server that fielded what is defined
231   * in the client protobuf service would pass in an implementation of the client blocking service
232   * and then its ClientService.BlockingInterface.class.  Used checking connection setup.
233   */
234  public static class BlockingServiceAndInterface {
235    private final BlockingService service;
236    private final Class<?> serviceInterface;
237    public BlockingServiceAndInterface(final BlockingService service,
238        final Class<?> serviceInterface) {
239      this.service = service;
240      this.serviceInterface = serviceInterface;
241    }
242    public Class<?> getServiceInterface() {
243      return this.serviceInterface;
244    }
245    public BlockingService getBlockingService() {
246      return this.service;
247    }
248  }
249
250  /**
251   * Constructs a server listening on the named port and address.
252   * @param server hosting instance of {@link Server}. We will do authentications if an
253   * instance else pass null for no authentication check.
254   * @param name Used keying this rpc servers' metrics and for naming the Listener thread.
255   * @param services A list of services.
256   * @param bindAddress Where to listen
257   * @param conf
258   * @param scheduler
259   * @param reservoirEnabled Enable ByteBufferPool or not.
260   */
261  public RpcServer(final Server server, final String name,
262      final List<BlockingServiceAndInterface> services,
263      final InetSocketAddress bindAddress, Configuration conf,
264      RpcScheduler scheduler, boolean reservoirEnabled) throws IOException {
265    if (reservoirEnabled) {
266      int poolBufSize = conf.getInt(ByteBufferPool.BUFFER_SIZE_KEY,
267          ByteBufferPool.DEFAULT_BUFFER_SIZE);
268      // The max number of buffers to be pooled in the ByteBufferPool. The default value been
269      // selected based on the #handlers configured. When it is read request, 2 MB is the max size
270      // at which we will send back one RPC request. Means max we need 2 MB for creating the
271      // response cell block. (Well it might be much lesser than this because in 2 MB size calc, we
272      // include the heap size overhead of each cells also.) Considering 2 MB, we will need
273      // (2 * 1024 * 1024) / poolBufSize buffers to make the response cell block. Pool buffer size
274      // is by default 64 KB.
275      // In case of read request, at the end of the handler process, we will make the response
276      // cellblock and add the Call to connection's response Q and a single Responder thread takes
277      // connections and responses from that one by one and do the socket write. So there is chances
278      // that by the time a handler originated response is actually done writing to socket and so
279      // released the BBs it used, the handler might have processed one more read req. On an avg 2x
280      // we consider and consider that also for the max buffers to pool
281      int bufsForTwoMB = (2 * 1024 * 1024) / poolBufSize;
282      int maxPoolSize = conf.getInt(ByteBufferPool.MAX_POOL_SIZE_KEY,
283          conf.getInt(HConstants.REGION_SERVER_HANDLER_COUNT,
284              HConstants.DEFAULT_REGION_SERVER_HANDLER_COUNT) * bufsForTwoMB * 2);
285      this.reservoir = new ByteBufferPool(poolBufSize, maxPoolSize);
286      this.minSizeForReservoirUse = getMinSizeForReservoirUse(this.reservoir);
287    } else {
288      reservoir = null;
289      this.minSizeForReservoirUse = Integer.MAX_VALUE;// reservoir itself not in place.
290    }
291    this.server = server;
292    this.services = services;
293    this.bindAddress = bindAddress;
294    this.conf = conf;
295    // See declaration above for documentation on what this size is.
296    this.maxQueueSizeInBytes =
297      this.conf.getLong("hbase.ipc.server.max.callqueue.size", DEFAULT_MAX_CALLQUEUE_SIZE);
298
299    this.warnResponseTime = conf.getInt(WARN_RESPONSE_TIME, DEFAULT_WARN_RESPONSE_TIME);
300    this.warnResponseSize = conf.getInt(WARN_RESPONSE_SIZE, DEFAULT_WARN_RESPONSE_SIZE);
301    this.minClientRequestTimeout = conf.getInt(MIN_CLIENT_REQUEST_TIMEOUT,
302        DEFAULT_MIN_CLIENT_REQUEST_TIMEOUT);
303    this.maxRequestSize = conf.getInt(MAX_REQUEST_SIZE, DEFAULT_MAX_REQUEST_SIZE);
304
305    this.metrics = new MetricsHBaseServer(name, new MetricsHBaseServerWrapperImpl(this));
306    this.tcpNoDelay = conf.getBoolean("hbase.ipc.server.tcpnodelay", true);
307    this.tcpKeepAlive = conf.getBoolean("hbase.ipc.server.tcpkeepalive", true);
308
309    this.cellBlockBuilder = new CellBlockBuilder(conf);
310
311    this.authorize = conf.getBoolean(HADOOP_SECURITY_AUTHORIZATION, false);
312    this.userProvider = UserProvider.instantiate(conf);
313    this.isSecurityEnabled = userProvider.isHBaseSecurityEnabled();
314    if (isSecurityEnabled) {
315      saslProps = SaslUtil.initSaslProperties(conf.get("hbase.rpc.protection",
316        QualityOfProtection.AUTHENTICATION.name().toLowerCase(Locale.ROOT)));
317    } else {
318      saslProps = Collections.emptyMap();
319    }
320
321    this.scheduler = scheduler;
322  }
323
324  @VisibleForTesting
325  static int getMinSizeForReservoirUse(ByteBufferPool pool) {
326    return pool.getBufferSize() / 6;
327  }
328
329  @Override
330  public void onConfigurationChange(Configuration newConf) {
331    initReconfigurable(newConf);
332    if (scheduler instanceof ConfigurationObserver) {
333      ((ConfigurationObserver) scheduler).onConfigurationChange(newConf);
334    }
335  }
336
337  protected void initReconfigurable(Configuration confToLoad) {
338    this.allowFallbackToSimpleAuth = confToLoad.getBoolean(FALLBACK_TO_INSECURE_CLIENT_AUTH, false);
339    if (isSecurityEnabled && allowFallbackToSimpleAuth) {
340      LOG.warn("********* WARNING! *********");
341      LOG.warn("This server is configured to allow connections from INSECURE clients");
342      LOG.warn("(" + FALLBACK_TO_INSECURE_CLIENT_AUTH + " = true).");
343      LOG.warn("While this option is enabled, client identities cannot be secured, and user");
344      LOG.warn("impersonation is possible!");
345      LOG.warn("For secure operation, please disable SIMPLE authentication as soon as possible,");
346      LOG.warn("by setting " + FALLBACK_TO_INSECURE_CLIENT_AUTH + " = false in hbase-site.xml");
347      LOG.warn("****************************");
348    }
349  }
350
351  Configuration getConf() {
352    return conf;
353  }
354
355  @Override
356  public boolean isStarted() {
357    return this.started;
358  }
359
360  @Override
361  public void refreshAuthManager(PolicyProvider pp) {
362    // Ignore warnings that this should be accessed in a static way instead of via an instance;
363    // it'll break if you go via static route.
364    synchronized (authManager) {
365      authManager.refresh(this.conf, pp);
366    }
367  }
368
369  protected AuthenticationTokenSecretManager createSecretManager() {
370    if (!isSecurityEnabled) return null;
371    if (server == null) return null;
372    Configuration conf = server.getConfiguration();
373    long keyUpdateInterval =
374        conf.getLong("hbase.auth.key.update.interval", 24*60*60*1000);
375    long maxAge =
376        conf.getLong("hbase.auth.token.max.lifetime", 7*24*60*60*1000);
377    return new AuthenticationTokenSecretManager(conf, server.getZooKeeper(),
378        server.getServerName().toString(), keyUpdateInterval, maxAge);
379  }
380
381  public SecretManager<? extends TokenIdentifier> getSecretManager() {
382    return this.secretManager;
383  }
384
385  @SuppressWarnings("unchecked")
386  public void setSecretManager(SecretManager<? extends TokenIdentifier> secretManager) {
387    this.secretManager = (SecretManager<TokenIdentifier>) secretManager;
388  }
389
390  /**
391   * This is a server side method, which is invoked over RPC. On success
392   * the return response has protobuf response payload. On failure, the
393   * exception name and the stack trace are returned in the protobuf response.
394   */
395  @Override
396  public Pair<Message, CellScanner> call(RpcCall call,
397      MonitoredRPCHandler status) throws IOException {
398    try {
399      MethodDescriptor md = call.getMethod();
400      Message param = call.getParam();
401      status.setRPC(md.getName(), new Object[]{param},
402        call.getReceiveTime());
403      // TODO: Review after we add in encoded data blocks.
404      status.setRPCPacket(param);
405      status.resume("Servicing call");
406      //get an instance of the method arg type
407      HBaseRpcController controller = new HBaseRpcControllerImpl(call.getCellScanner());
408      controller.setCallTimeout(call.getTimeout());
409      Message result = call.getService().callBlockingMethod(md, controller, param);
410      long receiveTime = call.getReceiveTime();
411      long startTime = call.getStartTime();
412      long endTime = System.currentTimeMillis();
413      int processingTime = (int) (endTime - startTime);
414      int qTime = (int) (startTime - receiveTime);
415      int totalTime = (int) (endTime - receiveTime);
416      if (LOG.isTraceEnabled()) {
417        LOG.trace(CurCall.get().toString() +
418            ", response " + TextFormat.shortDebugString(result) +
419            " queueTime: " + qTime +
420            " processingTime: " + processingTime +
421            " totalTime: " + totalTime);
422      }
423      // Use the raw request call size for now.
424      long requestSize = call.getSize();
425      long responseSize = result.getSerializedSize();
426      if (call.isClientCellBlockSupported()) {
427        // Include the payload size in HBaseRpcController
428        responseSize += call.getResponseCellSize();
429      }
430
431      metrics.dequeuedCall(qTime);
432      metrics.processedCall(processingTime);
433      metrics.totalCall(totalTime);
434      metrics.receivedRequest(requestSize);
435      metrics.sentResponse(responseSize);
436      // log any RPC responses that are slower than the configured warn
437      // response time or larger than configured warning size
438      boolean tooSlow = (processingTime > warnResponseTime && warnResponseTime > -1);
439      boolean tooLarge = (responseSize > warnResponseSize && warnResponseSize > -1);
440      if (tooSlow || tooLarge) {
441        // when tagging, we let TooLarge trump TooSmall to keep output simple
442        // note that large responses will often also be slow.
443        logResponse(param,
444            md.getName(), md.getName() + "(" + param.getClass().getName() + ")",
445            (tooLarge ? "TooLarge" : "TooSlow"),
446            status.getClient(), startTime, processingTime, qTime,
447            responseSize);
448      }
449      return new Pair<>(result, controller.cellScanner());
450    } catch (Throwable e) {
451      // The above callBlockingMethod will always return a SE.  Strip the SE wrapper before
452      // putting it on the wire.  Its needed to adhere to the pb Service Interface but we don't
453      // need to pass it over the wire.
454      if (e instanceof ServiceException) {
455        if (e.getCause() == null) {
456          LOG.debug("Caught a ServiceException with null cause", e);
457        } else {
458          e = e.getCause();
459        }
460      }
461
462      // increment the number of requests that were exceptions.
463      metrics.exception(e);
464
465      if (e instanceof LinkageError) throw new DoNotRetryIOException(e);
466      if (e instanceof IOException) throw (IOException)e;
467      LOG.error("Unexpected throwable object ", e);
468      throw new IOException(e.getMessage(), e);
469    }
470  }
471
472  /**
473   * Logs an RPC response to the LOG file, producing valid JSON objects for
474   * client Operations.
475   * @param param The parameters received in the call.
476   * @param methodName The name of the method invoked
477   * @param call The string representation of the call
478   * @param tag  The tag that will be used to indicate this event in the log.
479   * @param clientAddress   The address of the client who made this call.
480   * @param startTime       The time that the call was initiated, in ms.
481   * @param processingTime  The duration that the call took to run, in ms.
482   * @param qTime           The duration that the call spent on the queue
483   *                        prior to being initiated, in ms.
484   * @param responseSize    The size in bytes of the response buffer.
485   */
486  void logResponse(Message param, String methodName, String call, String tag,
487      String clientAddress, long startTime, int processingTime, int qTime,
488      long responseSize) throws IOException {
489    // base information that is reported regardless of type of call
490    Map<String, Object> responseInfo = new HashMap<>();
491    responseInfo.put("starttimems", startTime);
492    responseInfo.put("processingtimems", processingTime);
493    responseInfo.put("queuetimems", qTime);
494    responseInfo.put("responsesize", responseSize);
495    responseInfo.put("client", clientAddress);
496    responseInfo.put("class", server == null? "": server.getClass().getSimpleName());
497    responseInfo.put("method", methodName);
498    responseInfo.put("call", call);
499    responseInfo.put("param", ProtobufUtil.getShortTextFormat(param));
500    if (param instanceof ClientProtos.ScanRequest && rsRpcServices != null) {
501      ClientProtos.ScanRequest request = ((ClientProtos.ScanRequest) param);
502      if (request.hasScannerId()) {
503        long scannerId = request.getScannerId();
504        String scanDetails = rsRpcServices.getScanDetailsWithId(scannerId);
505        if (scanDetails != null) {
506          responseInfo.put("scandetails", scanDetails);
507        }
508      }
509    }
510    LOG.warn("(response" + tag + "): " + MAPPER.writeValueAsString(responseInfo));
511  }
512
513  /**
514   * Set the handler for calling out of RPC for error conditions.
515   * @param handler the handler implementation
516   */
517  @Override
518  public void setErrorHandler(HBaseRPCErrorHandler handler) {
519    this.errorHandler = handler;
520  }
521
522  @Override
523  public HBaseRPCErrorHandler getErrorHandler() {
524    return this.errorHandler;
525  }
526
527  /**
528   * Returns the metrics instance for reporting RPC call statistics
529   */
530  @Override
531  public MetricsHBaseServer getMetrics() {
532    return metrics;
533  }
534
535  @Override
536  public void addCallSize(final long diff) {
537    this.callQueueSizeInBytes.add(diff);
538  }
539
540  /**
541   * Authorize the incoming client connection.
542   * @param user client user
543   * @param connection incoming connection
544   * @param addr InetAddress of incoming connection
545   * @throws AuthorizationException when the client isn't authorized to talk the protocol
546   */
547  public void authorize(UserGroupInformation user, ConnectionHeader connection,
548      InetAddress addr) throws AuthorizationException {
549    if (authorize) {
550      Class<?> c = getServiceInterface(services, connection.getServiceName());
551      synchronized (authManager) {
552        authManager.authorize(user, c, getConf(), addr);
553      }
554    }
555  }
556
557  /**
558   * When the read or write buffer size is larger than this limit, i/o will be
559   * done in chunks of this size. Most RPC requests and responses would be
560   * be smaller.
561   */
562  protected static final int NIO_BUFFER_LIMIT = 64 * 1024; //should not be more than 64KB.
563
564  /**
565   * This is a wrapper around {@link java.nio.channels.ReadableByteChannel#read(java.nio.ByteBuffer)}.
566   * If the amount of data is large, it writes to channel in smaller chunks.
567   * This is to avoid jdk from creating many direct buffers as the size of
568   * ByteBuffer increases. There should not be any performance degredation.
569   *
570   * @param channel writable byte channel to write on
571   * @param buffer buffer to write
572   * @return number of bytes written
573   * @throws java.io.IOException e
574   * @see java.nio.channels.ReadableByteChannel#read(java.nio.ByteBuffer)
575   */
576  protected int channelRead(ReadableByteChannel channel,
577                                   ByteBuffer buffer) throws IOException {
578
579    int count = (buffer.remaining() <= NIO_BUFFER_LIMIT) ?
580           channel.read(buffer) : channelIO(channel, null, buffer);
581    if (count > 0) {
582      metrics.receivedBytes(count);
583    }
584    return count;
585  }
586
587  /**
588   * Helper for {@link #channelRead(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer).
589   * Only one of readCh or writeCh should be non-null.
590   *
591   * @param readCh read channel
592   * @param writeCh write channel
593   * @param buf buffer to read or write into/out of
594   * @return bytes written
595   * @throws java.io.IOException e
596   * @see #channelRead(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer)
597   */
598  private static int channelIO(ReadableByteChannel readCh,
599                               WritableByteChannel writeCh,
600                               ByteBuffer buf) throws IOException {
601
602    int originalLimit = buf.limit();
603    int initialRemaining = buf.remaining();
604    int ret = 0;
605
606    while (buf.remaining() > 0) {
607      try {
608        int ioSize = Math.min(buf.remaining(), NIO_BUFFER_LIMIT);
609        buf.limit(buf.position() + ioSize);
610
611        ret = (readCh == null) ? writeCh.write(buf) : readCh.read(buf);
612
613        if (ret < ioSize) {
614          break;
615        }
616
617      } finally {
618        buf.limit(originalLimit);
619      }
620    }
621
622    int nBytes = initialRemaining - buf.remaining();
623    return (nBytes > 0) ? nBytes : ret;
624  }
625
626  /**
627   * This is extracted to a static method for better unit testing. We try to get buffer(s) from pool
628   * as much as possible.
629   *
630   * @param pool The ByteBufferPool to use
631   * @param minSizeForPoolUse Only for buffer size above this, we will try to use pool. Any buffer
632   *           need of size below this, create on heap ByteBuffer.
633   * @param reqLen Bytes count in request
634   */
635  @VisibleForTesting
636  static Pair<ByteBuff, CallCleanup> allocateByteBuffToReadInto(ByteBufferPool pool,
637      int minSizeForPoolUse, int reqLen) {
638    ByteBuff resultBuf;
639    List<ByteBuffer> bbs = new ArrayList<>((reqLen / pool.getBufferSize()) + 1);
640    int remain = reqLen;
641    ByteBuffer buf = null;
642    while (remain >= minSizeForPoolUse && (buf = pool.getBuffer()) != null) {
643      bbs.add(buf);
644      remain -= pool.getBufferSize();
645    }
646    ByteBuffer[] bufsFromPool = null;
647    if (bbs.size() > 0) {
648      bufsFromPool = new ByteBuffer[bbs.size()];
649      bbs.toArray(bufsFromPool);
650    }
651    if (remain > 0) {
652      bbs.add(ByteBuffer.allocate(remain));
653    }
654    if (bbs.size() > 1) {
655      ByteBuffer[] items = new ByteBuffer[bbs.size()];
656      bbs.toArray(items);
657      resultBuf = new MultiByteBuff(items);
658    } else {
659      // We are backed by single BB
660      resultBuf = new SingleByteBuff(bbs.get(0));
661    }
662    resultBuf.limit(reqLen);
663    if (bufsFromPool != null) {
664      final ByteBuffer[] bufsFromPoolFinal = bufsFromPool;
665      return new Pair<>(resultBuf, () -> {
666        // Return back all the BBs to pool
667        for (int i = 0; i < bufsFromPoolFinal.length; i++) {
668          pool.putbackBuffer(bufsFromPoolFinal[i]);
669        }
670      });
671    }
672    return new Pair<>(resultBuf, null);
673  }
674
675  /**
676   * Needed for features such as delayed calls.  We need to be able to store the current call
677   * so that we can complete it later or ask questions of what is supported by the current ongoing
678   * call.
679   * @return An RpcCallContext backed by the currently ongoing call (gotten from a thread local)
680   */
681  public static Optional<RpcCall> getCurrentCall() {
682    return Optional.ofNullable(CurCall.get());
683  }
684
685  public static boolean isInRpcCallContext() {
686    return CurCall.get() != null;
687  }
688
689  /**
690   * Returns the user credentials associated with the current RPC request or not present if no
691   * credentials were provided.
692   * @return A User
693   */
694  public static Optional<User> getRequestUser() {
695    Optional<RpcCall> ctx = getCurrentCall();
696    return ctx.isPresent() ? ctx.get().getRequestUser() : Optional.empty();
697  }
698
699  /**
700   * The number of open RPC conections
701   * @return the number of open rpc connections
702   */
703  abstract public int getNumOpenConnections();
704
705  /**
706   * Returns the username for any user associated with the current RPC
707   * request or not present if no user is set.
708   */
709  public static Optional<String> getRequestUserName() {
710    return getRequestUser().map(User::getShortName);
711  }
712
713  /**
714   * @return Address of remote client if a request is ongoing, else null
715   */
716  public static Optional<InetAddress> getRemoteAddress() {
717    return getCurrentCall().map(RpcCall::getRemoteAddress);
718  }
719
720  /**
721   * @param serviceName Some arbitrary string that represents a 'service'.
722   * @param services Available service instances
723   * @return Matching BlockingServiceAndInterface pair
724   */
725  protected static BlockingServiceAndInterface getServiceAndInterface(
726      final List<BlockingServiceAndInterface> services, final String serviceName) {
727    for (BlockingServiceAndInterface bs : services) {
728      if (bs.getBlockingService().getDescriptorForType().getName().equals(serviceName)) {
729        return bs;
730      }
731    }
732    return null;
733  }
734
735  /**
736   * @param serviceName Some arbitrary string that represents a 'service'.
737   * @param services Available services and their service interfaces.
738   * @return Service interface class for <code>serviceName</code>
739   */
740  protected static Class<?> getServiceInterface(
741      final List<BlockingServiceAndInterface> services,
742      final String serviceName) {
743    BlockingServiceAndInterface bsasi =
744        getServiceAndInterface(services, serviceName);
745    return bsasi == null? null: bsasi.getServiceInterface();
746  }
747
748  /**
749   * @param serviceName Some arbitrary string that represents a 'service'.
750   * @param services Available services and their service interfaces.
751   * @return BlockingService that goes with the passed <code>serviceName</code>
752   */
753  protected static BlockingService getService(
754      final List<BlockingServiceAndInterface> services,
755      final String serviceName) {
756    BlockingServiceAndInterface bsasi =
757        getServiceAndInterface(services, serviceName);
758    return bsasi == null? null: bsasi.getBlockingService();
759  }
760
761  protected static MonitoredRPCHandler getStatus() {
762    // It is ugly the way we park status up in RpcServer.  Let it be for now.  TODO.
763    MonitoredRPCHandler status = RpcServer.MONITORED_RPC.get();
764    if (status != null) {
765      return status;
766    }
767    status = TaskMonitor.get().createRPCStatus(Thread.currentThread().getName());
768    status.pause("Waiting for a call");
769    RpcServer.MONITORED_RPC.set(status);
770    return status;
771  }
772
773  /** Returns the remote side ip address when invoked inside an RPC
774   *  Returns null incase of an error.
775   *  @return InetAddress
776   */
777  public static InetAddress getRemoteIp() {
778    RpcCall call = CurCall.get();
779    if (call != null) {
780      return call.getRemoteAddress();
781    }
782    return null;
783  }
784
785  @Override
786  public RpcScheduler getScheduler() {
787    return scheduler;
788  }
789
790  @Override
791  public void setRsRpcServices(RSRpcServices rsRpcServices) {
792    this.rsRpcServices = rsRpcServices;
793  }
794}