View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.ipc;
20  
21  import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION;
22  
23  import com.google.common.util.concurrent.ThreadFactoryBuilder;
24  import com.google.protobuf.BlockingService;
25  import com.google.protobuf.CodedInputStream;
26  import com.google.protobuf.CodedOutputStream;
27  import com.google.protobuf.Descriptors.MethodDescriptor;
28  import com.google.protobuf.Message;
29  import com.google.protobuf.ServiceException;
30  import com.google.protobuf.TextFormat;
31  
32  import java.io.ByteArrayInputStream;
33  import java.io.ByteArrayOutputStream;
34  import java.io.DataOutputStream;
35  import java.io.IOException;
36  import java.io.InputStream;
37  import java.net.BindException;
38  import java.net.InetAddress;
39  import java.net.InetSocketAddress;
40  import java.net.ServerSocket;
41  import java.net.Socket;
42  import java.net.SocketException;
43  import java.net.UnknownHostException;
44  import java.nio.ByteBuffer;
45  import java.nio.channels.CancelledKeyException;
46  import java.nio.channels.Channels;
47  import java.nio.channels.ClosedChannelException;
48  import java.nio.channels.GatheringByteChannel;
49  import java.nio.channels.ReadableByteChannel;
50  import java.nio.channels.SelectionKey;
51  import java.nio.channels.Selector;
52  import java.nio.channels.ServerSocketChannel;
53  import java.nio.channels.SocketChannel;
54  import java.nio.channels.WritableByteChannel;
55  import java.security.PrivilegedExceptionAction;
56  import java.util.ArrayList;
57  import java.util.Collections;
58  import java.util.HashMap;
59  import java.util.Iterator;
60  import java.util.LinkedList;
61  import java.util.List;
62  import java.util.Map;
63  import java.util.Random;
64  import java.util.Set;
65  import java.util.concurrent.ConcurrentHashMap;
66  import java.util.concurrent.ConcurrentLinkedDeque;
67  import java.util.concurrent.ExecutorService;
68  import java.util.concurrent.Executors;
69  import java.util.concurrent.locks.Lock;
70  import java.util.concurrent.locks.ReentrantLock;
71  
72  import javax.security.sasl.Sasl;
73  import javax.security.sasl.SaslException;
74  import javax.security.sasl.SaslServer;
75  
76  import org.apache.commons.logging.Log;
77  import org.apache.commons.logging.LogFactory;
78  import org.apache.hadoop.conf.Configuration;
79  import org.apache.hadoop.hbase.CallQueueTooBigException;
80  import org.apache.hadoop.hbase.CellScanner;
81  import org.apache.hadoop.hbase.DoNotRetryIOException;
82  import org.apache.hadoop.hbase.HBaseIOException;
83  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
84  import org.apache.hadoop.hbase.HConstants;
85  import org.apache.hadoop.hbase.Server;
86  import org.apache.hadoop.hbase.classification.InterfaceAudience;
87  import org.apache.hadoop.hbase.classification.InterfaceStability;
88  import org.apache.hadoop.hbase.client.NeedUnmanagedConnectionException;
89  import org.apache.hadoop.hbase.client.VersionInfoUtil;
90  import org.apache.hadoop.hbase.codec.Codec;
91  import org.apache.hadoop.hbase.conf.ConfigurationObserver;
92  import org.apache.hadoop.hbase.exceptions.RegionMovedException;
93  import org.apache.hadoop.hbase.exceptions.RequestTooBigException;
94  import org.apache.hadoop.hbase.io.BoundedByteBufferPool;
95  import org.apache.hadoop.hbase.io.ByteBufferInputStream;
96  import org.apache.hadoop.hbase.io.ByteBufferOutputStream;
97  import org.apache.hadoop.hbase.monitoring.MonitoredRPCHandler;
98  import org.apache.hadoop.hbase.monitoring.TaskMonitor;
99  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
100 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
101 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.VersionInfo;
102 import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.CellBlockMeta;
103 import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.ConnectionHeader;
104 import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.ExceptionResponse;
105 import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.RequestHeader;
106 import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.ResponseHeader;
107 import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.UserInformation;
108 import org.apache.hadoop.hbase.regionserver.RSRpcServices;
109 import org.apache.hadoop.hbase.security.AccessDeniedException;
110 import org.apache.hadoop.hbase.security.AuthMethod;
111 import org.apache.hadoop.hbase.security.HBasePolicyProvider;
112 import org.apache.hadoop.hbase.security.HBaseSaslRpcServer;
113 import org.apache.hadoop.hbase.security.HBaseSaslRpcServer.SaslDigestCallbackHandler;
114 import org.apache.hadoop.hbase.security.HBaseSaslRpcServer.SaslGssCallbackHandler;
115 import org.apache.hadoop.hbase.security.SaslStatus;
116 import org.apache.hadoop.hbase.security.SaslUtil;
117 import org.apache.hadoop.hbase.security.User;
118 import org.apache.hadoop.hbase.security.UserProvider;
119 import org.apache.hadoop.hbase.security.token.AuthenticationTokenSecretManager;
120 import org.apache.hadoop.hbase.util.Bytes;
121 import org.apache.hadoop.hbase.util.Counter;
122 import org.apache.hadoop.hbase.util.Pair;
123 import org.apache.hadoop.hbase.util.Threads;
124 import org.apache.hadoop.io.BytesWritable;
125 import org.apache.hadoop.io.IntWritable;
126 import org.apache.hadoop.io.Writable;
127 import org.apache.hadoop.io.WritableUtils;
128 import org.apache.hadoop.io.compress.CompressionCodec;
129 import org.apache.hadoop.security.UserGroupInformation;
130 import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod;
131 import org.apache.hadoop.security.authorize.AuthorizationException;
132 import org.apache.hadoop.security.authorize.PolicyProvider;
133 import org.apache.hadoop.security.authorize.ProxyUsers;
134 import org.apache.hadoop.security.authorize.ServiceAuthorizationManager;
135 import org.apache.hadoop.security.token.SecretManager;
136 import org.apache.hadoop.security.token.SecretManager.InvalidToken;
137 import org.apache.hadoop.security.token.TokenIdentifier;
138 import org.apache.hadoop.util.StringUtils;
139 import org.apache.htrace.TraceInfo;
140 import org.codehaus.jackson.map.ObjectMapper;
141 
142 /**
143  * An RPC server that hosts protobuf described Services.
144  *
145  * An RpcServer instance has a Listener that hosts the socket.  Listener has fixed number
146  * of Readers in an ExecutorPool, 10 by default.  The Listener does an accept and then
147  * round robin a Reader is chosen to do the read.  The reader is registered on Selector.  Read does
148  * total read off the channel and the parse from which it makes a Call.  The call is wrapped in a
149  * CallRunner and passed to the scheduler to be run.  Reader goes back to see if more to be done
150  * and loops till done.
151  *
152  * <p>Scheduler can be variously implemented but default simple scheduler has handlers to which it
153  * has given the queues into which calls (i.e. CallRunner instances) are inserted.  Handlers run
154  * taking from the queue.  They run the CallRunner#run method on each item gotten from queue
155  * and keep taking while the server is up.
156  *
157  * CallRunner#run executes the call.  When done, asks the included Call to put itself on new
158  * queue for Responder to pull from and return result to client.
159  */
160 @InterfaceAudience.LimitedPrivate({HBaseInterfaceAudience.COPROC, HBaseInterfaceAudience.PHOENIX})
161 @InterfaceStability.Evolving
162 public class RpcServer implements RpcServerInterface, ConfigurationObserver {
163   // LOG is being used in CallRunner and the log level is being changed in tests
164   public static final Log LOG = LogFactory.getLog(RpcServer.class);
165   private static final CallQueueTooBigException CALL_QUEUE_TOO_BIG_EXCEPTION
166       = new CallQueueTooBigException();
167 
168   private final boolean authorize;
169   private boolean isSecurityEnabled;
170 
171   public static final byte CURRENT_VERSION = 0;
172 
173   /**
174    * Whether we allow a fallback to SIMPLE auth for insecure clients when security is enabled.
175    */
176   public static final String FALLBACK_TO_INSECURE_CLIENT_AUTH =
177           "hbase.ipc.server.fallback-to-simple-auth-allowed";
178 
179   /**
180    * How many calls/handler are allowed in the queue.
181    */
182   static final int DEFAULT_MAX_CALLQUEUE_LENGTH_PER_HANDLER = 10;
183 
184   /**
185    * The maximum size that we can hold in the RPC queue
186    */
187   private static final int DEFAULT_MAX_CALLQUEUE_SIZE = 1024 * 1024 * 1024;
188 
189   private final CellBlockBuilder cellBlockBuilder;
190 
191   private static final String AUTH_FAILED_FOR = "Auth failed for ";
192   private static final String AUTH_SUCCESSFUL_FOR = "Auth successful for ";
193   private static final Log AUDITLOG = LogFactory.getLog("SecurityLogger." +
194     Server.class.getName());
195   protected SecretManager<TokenIdentifier> secretManager;
196   protected ServiceAuthorizationManager authManager;
197 
198   /** This is set to Call object before Handler invokes an RPC and ybdie
199    * after the call returns.
200    */
201   protected static final ThreadLocal<Call> CurCall = new ThreadLocal<Call>();
202 
203   /** Keeps MonitoredRPCHandler per handler thread. */
204   static final ThreadLocal<MonitoredRPCHandler> MONITORED_RPC
205       = new ThreadLocal<MonitoredRPCHandler>();
206 
207   protected final InetSocketAddress bindAddress;
208   protected int port;                             // port we listen on
209   protected InetSocketAddress address;            // inet address we listen on
210   private int readThreads;                        // number of read threads
211   protected int maxIdleTime;                      // the maximum idle time after
212                                                   // which a client may be
213                                                   // disconnected
214   protected int thresholdIdleConnections;         // the number of idle
215                                                   // connections after which we
216                                                   // will start cleaning up idle
217                                                   // connections
218   int maxConnectionsToNuke;                       // the max number of
219                                                   // connections to nuke
220                                                   // during a cleanup
221 
222   protected MetricsHBaseServer metrics;
223 
224   protected final Configuration conf;
225 
226   private int maxQueueSize;
227   protected int socketSendBufferSize;
228   protected final boolean tcpNoDelay;   // if T then disable Nagle's Algorithm
229   protected final boolean tcpKeepAlive; // if T then use keepalives
230   protected final long purgeTimeout;    // in milliseconds
231 
232   /**
233    * This flag is used to indicate to sub threads when they should go down.  When we call
234    * {@link #start()}, all threads started will consult this flag on whether they should
235    * keep going.  It is set to false when {@link #stop()} is called.
236    */
237   volatile boolean running = true;
238 
239   /**
240    * This flag is set to true after all threads are up and 'running' and the server is then opened
241    * for business by the call to {@link #start()}.
242    */
243   volatile boolean started = false;
244 
245   /**
246    * This is a running count of the size of all outstanding calls by size.
247    */
248   protected final Counter callQueueSize = new Counter();
249 
250   protected final List<Connection> connectionList =
251     Collections.synchronizedList(new LinkedList<Connection>());
252   //maintain a list
253   //of client connections
254   private Listener listener = null;
255   protected Responder responder = null;
256   protected AuthenticationTokenSecretManager authTokenSecretMgr = null;
257   protected int numConnections = 0;
258 
259   protected HBaseRPCErrorHandler errorHandler = null;
260 
261   public static final String MAX_REQUEST_SIZE = "hbase.ipc.max.request.size";
262   private static final RequestTooBigException REQUEST_TOO_BIG_EXCEPTION =
263       new RequestTooBigException();
264 
265   private static final String WARN_RESPONSE_TIME = "hbase.ipc.warn.response.time";
266   private static final String WARN_RESPONSE_SIZE = "hbase.ipc.warn.response.size";
267 
268 
269   /**
270    * Minimum allowable timeout (in milliseconds) in rpc request's header. This
271    * configuration exists to prevent the rpc service regarding this request as timeout immediately.
272    */
273   private static final String MIN_CLIENT_REQUEST_TIMEOUT = "hbase.ipc.min.client.request.timeout";
274   private static final int DEFAULT_MIN_CLIENT_REQUEST_TIMEOUT = 20;
275 
276   /** Default value for above params */
277   public static final int DEFAULT_MAX_REQUEST_SIZE = DEFAULT_MAX_CALLQUEUE_SIZE / 4; // 256M
278   private static final int DEFAULT_WARN_RESPONSE_TIME = 10000; // milliseconds
279   private static final int DEFAULT_WARN_RESPONSE_SIZE = 100 * 1024 * 1024;
280 
281   private static final ObjectMapper MAPPER = new ObjectMapper();
282 
283   private final int maxRequestSize;
284   private final int warnResponseTime;
285   private final int warnResponseSize;
286 
287   private final int minClientRequestTimeout;
288 
289   private final Server server;
290   private final List<BlockingServiceAndInterface> services;
291 
292   private final RpcScheduler scheduler;
293 
294   private UserProvider userProvider;
295 
296   private final BoundedByteBufferPool reservoir;
297 
298   private volatile boolean allowFallbackToSimpleAuth;
299 
300   /**
301    * Used to get details for scan with a scanner_id<br/>
302    * TODO try to figure out a better way and remove reference from regionserver package later.
303    */
304   private RSRpcServices rsRpcServices;
305 
306   /**
307    * Datastructure that holds all necessary to a method invocation and then afterward, carries
308    * the result.
309    */
310   @InterfaceAudience.LimitedPrivate({HBaseInterfaceAudience.COPROC, HBaseInterfaceAudience.PHOENIX})
311   @InterfaceStability.Evolving
312   public class Call implements RpcCallContext {
313     protected int id;                             // the client's call id
314     protected BlockingService service;
315     protected MethodDescriptor md;
316     protected RequestHeader header;
317     protected Message param;                      // the parameter passed
318     // Optional cell data passed outside of protobufs.
319     protected CellScanner cellScanner;
320     protected Connection connection;              // connection to client
321     protected long timestamp;      // the time received when response is null
322                                    // the time served when response is not null
323     protected int timeout;
324     protected long startTime;
325     protected long deadline;// the deadline to handle this call, if exceed we can drop it.
326 
327     /**
328      * Chain of buffers to send as response.
329      */
330     protected BufferChain response;
331     protected Responder responder;
332 
333     protected long size;                          // size of current call
334     protected boolean isError;
335     protected TraceInfo tinfo;
336     private ByteBuffer cellBlock = null;
337 
338     private User user;
339     private InetAddress remoteAddress;
340 
341     private long responseCellSize = 0;
342     private long responseBlockSize = 0;
343     // cumulative size of serialized exceptions
344     private long exceptionSize = 0;
345     private boolean retryImmediatelySupported;
346 
347     @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NP_NULL_ON_SOME_PATH",
348         justification="Can't figure why this complaint is happening... see below")
349     Call(int id, final BlockingService service, final MethodDescriptor md, RequestHeader header,
350          Message param, CellScanner cellScanner, Connection connection, Responder responder,
351          long size, TraceInfo tinfo, final InetAddress remoteAddress, int timeout) {
352       this.id = id;
353       this.service = service;
354       this.md = md;
355       this.header = header;
356       this.param = param;
357       this.cellScanner = cellScanner;
358       this.connection = connection;
359       this.timestamp = System.currentTimeMillis();
360       this.response = null;
361       this.responder = responder;
362       this.isError = false;
363       this.size = size;
364       this.tinfo = tinfo;
365       this.user = connection == null? null: connection.user; // FindBugs: NP_NULL_ON_SOME_PATH
366       this.remoteAddress = remoteAddress;
367       this.retryImmediatelySupported =
368           connection == null? null: connection.retryImmediatelySupported;
369       this.timeout = timeout;
370       this.deadline = this.timeout > 0 ? this.timestamp + this.timeout : Long.MAX_VALUE;
371     }
372 
373     /**
374      * Call is done. Execution happened and we returned results to client. It is now safe to
375      * cleanup.
376      */
377     @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="IS2_INCONSISTENT_SYNC",
378         justification="Presume the lock on processing request held by caller is protection enough")
379     void done() {
380       if (this.cellBlock != null && reservoir != null) {
381         // Return buffer to reservoir now we are done with it.
382         reservoir.putBuffer(this.cellBlock);
383         this.cellBlock = null;
384       }
385       this.connection.decRpcCount();  // Say that we're done with this call.
386     }
387 
388     @Override
389     public String toString() {
390       return toShortString() + " param: " +
391         (this.param != null? ProtobufUtil.getShortTextFormat(this.param): "") +
392         " connection: " + connection.toString();
393     }
394 
395     protected RequestHeader getHeader() {
396       return this.header;
397     }
398 
399     public boolean hasPriority() {
400       return this.header.hasPriority();
401     }
402 
403     public int getPriority() {
404       return this.header.getPriority();
405     }
406 
407     /*
408      * Short string representation without param info because param itself could be huge depends on
409      * the payload of a command
410      */
411     String toShortString() {
412       String serviceName = this.connection.service != null ?
413           this.connection.service.getDescriptorForType().getName() : "null";
414       return "callId: " + this.id + " service: " + serviceName +
415           " methodName: " + ((this.md != null) ? this.md.getName() : "n/a") +
416           " size: " + StringUtils.TraditionalBinaryPrefix.long2String(this.size, "", 1) +
417           " connection: " + connection.toString() +
418           " deadline: " + deadline;
419     }
420 
421     String toTraceString() {
422       String serviceName = this.connection.service != null ?
423                            this.connection.service.getDescriptorForType().getName() : "";
424       String methodName = (this.md != null) ? this.md.getName() : "";
425       return serviceName + "." + methodName;
426     }
427 
428     protected synchronized void setSaslTokenResponse(ByteBuffer response) {
429       this.response = new BufferChain(response);
430     }
431 
432     protected synchronized void setResponse(Object m, final CellScanner cells,
433         Throwable t, String errorMsg) {
434       if (this.isError) return;
435       if (t != null) this.isError = true;
436       BufferChain bc = null;
437       try {
438         ResponseHeader.Builder headerBuilder = ResponseHeader.newBuilder();
439         // Presume it a pb Message.  Could be null.
440         Message result = (Message)m;
441         // Call id.
442         headerBuilder.setCallId(this.id);
443         if (t != null) {
444           ExceptionResponse.Builder exceptionBuilder = ExceptionResponse.newBuilder();
445           exceptionBuilder.setExceptionClassName(t.getClass().getName());
446           exceptionBuilder.setStackTrace(errorMsg);
447           exceptionBuilder.setDoNotRetry(t instanceof DoNotRetryIOException ||
448             t instanceof NeedUnmanagedConnectionException);
449           if (t instanceof RegionMovedException) {
450             // Special casing for this exception.  This is only one carrying a payload.
451             // Do this instead of build a generic system for allowing exceptions carry
452             // any kind of payload.
453             RegionMovedException rme = (RegionMovedException)t;
454             exceptionBuilder.setHostname(rme.getHostname());
455             exceptionBuilder.setPort(rme.getPort());
456           }
457           // Set the exception as the result of the method invocation.
458           headerBuilder.setException(exceptionBuilder.build());
459         }
460         // Pass reservoir to buildCellBlock. Keep reference to returne so can add it back to the
461         // reservoir when finished. This is hacky and the hack is not contained but benefits are
462         // high when we can avoid a big buffer allocation on each rpc.
463         this.cellBlock = cellBlockBuilder.buildCellBlock(this.connection.codec,
464           this.connection.compressionCodec, cells, reservoir);
465         if (this.cellBlock != null) {
466           CellBlockMeta.Builder cellBlockBuilder = CellBlockMeta.newBuilder();
467           // Presumes the cellBlock bytebuffer has been flipped so limit has total size in it.
468           cellBlockBuilder.setLength(this.cellBlock.limit());
469           headerBuilder.setCellBlockMeta(cellBlockBuilder.build());
470         }
471         Message header = headerBuilder.build();
472 
473         byte[] b = createHeaderAndMessageBytes(result, header);
474 
475         bc = new BufferChain(ByteBuffer.wrap(b), this.cellBlock);
476 
477         if (connection.useWrap) {
478           bc = wrapWithSasl(bc);
479         }
480       } catch (IOException e) {
481         LOG.warn("Exception while creating response " + e);
482       }
483       this.response = bc;
484     }
485 
486     private byte[] createHeaderAndMessageBytes(Message result, Message header)
487         throws IOException {
488       // Organize the response as a set of bytebuffers rather than collect it all together inside
489       // one big byte array; save on allocations.
490       int headerSerializedSize = 0, resultSerializedSize = 0, headerVintSize = 0,
491           resultVintSize = 0;
492       if (header != null) {
493         headerSerializedSize = header.getSerializedSize();
494         headerVintSize = CodedOutputStream.computeRawVarint32Size(headerSerializedSize);
495       }
496       if (result != null) {
497         resultSerializedSize = result.getSerializedSize();
498         resultVintSize = CodedOutputStream.computeRawVarint32Size(resultSerializedSize);
499       }
500       // calculate the total size
501       int totalSize = headerSerializedSize + headerVintSize
502           + (resultSerializedSize + resultVintSize)
503           + (this.cellBlock == null ? 0 : this.cellBlock.limit());
504       // The byte[] should also hold the totalSize of the header, message and the cellblock
505       byte[] b = new byte[headerSerializedSize + headerVintSize + resultSerializedSize
506           + resultVintSize + Bytes.SIZEOF_INT];
507       // The RpcClient expects the int to be in a format that code be decoded by
508       // the DataInputStream#readInt(). Hence going with the Bytes.toBytes(int)
509       // form of writing int.
510       Bytes.putInt(b, 0, totalSize);
511       CodedOutputStream cos = CodedOutputStream.newInstance(b, Bytes.SIZEOF_INT,
512           b.length - Bytes.SIZEOF_INT);
513       if (header != null) {
514         cos.writeMessageNoTag(header);
515       }
516       if (result != null) {
517         cos.writeMessageNoTag(result);
518       }
519       cos.flush();
520       cos.checkNoSpaceLeft();
521       return b;
522     }
523 
524     private BufferChain wrapWithSasl(BufferChain bc)
525         throws IOException {
526       if (!this.connection.useSasl) return bc;
527       // Looks like no way around this; saslserver wants a byte array.  I have to make it one.
528       // THIS IS A BIG UGLY COPY.
529       byte [] responseBytes = bc.getBytes();
530       byte [] token;
531       // synchronization may be needed since there can be multiple Handler
532       // threads using saslServer to wrap responses.
533       synchronized (connection.saslServer) {
534         token = connection.saslServer.wrap(responseBytes, 0, responseBytes.length);
535       }
536       if (LOG.isTraceEnabled()) {
537         LOG.trace("Adding saslServer wrapped token of size " + token.length
538             + " as call response.");
539       }
540 
541       ByteBuffer bbTokenLength = ByteBuffer.wrap(Bytes.toBytes(token.length));
542       ByteBuffer bbTokenBytes = ByteBuffer.wrap(token);
543       return new BufferChain(bbTokenLength, bbTokenBytes);
544     }
545 
546     @Override
547     public boolean isClientCellBlockSupported() {
548       return this.connection != null && this.connection.codec != null;
549     }
550 
551     @Override
552     public long disconnectSince() {
553       if (!connection.channel.isOpen()) {
554         return System.currentTimeMillis() - timestamp;
555       } else {
556         return -1L;
557       }
558     }
559 
560     @Override
561     public long getResponseExceptionSize() {
562       return exceptionSize;
563     }
564     @Override
565     public void incrementResponseExceptionSize(long exSize) {
566       exceptionSize += exSize;
567     }
568 
569     public long getSize() {
570       return this.size;
571     }
572 
573     @Override
574     public long getResponseCellSize() {
575       return responseCellSize;
576     }
577 
578     @Override
579     public void incrementResponseCellSize(long cellSize) {
580       responseCellSize += cellSize;
581     }
582 
583     @Override
584     public long getResponseBlockSize() {
585       return responseBlockSize;
586     }
587 
588     @Override
589     public void incrementResponseBlockSize(long blockSize) {
590       responseBlockSize += blockSize;
591     }
592 
593     @Override
594     public long getDeadline() {
595       return deadline;
596     }
597 
598     public synchronized void sendResponseIfReady() throws IOException {
599       // set param null to reduce memory pressure
600       this.param = null;
601       this.responder.doRespond(this);
602     }
603 
604     public UserGroupInformation getRemoteUser() {
605       return connection.ugi;
606     }
607 
608     @Override
609     public User getRequestUser() {
610       return user;
611     }
612 
613     @Override
614     public String getRequestUserName() {
615       User user = getRequestUser();
616       return user == null? null: user.getShortName();
617     }
618 
619     @Override
620     public InetAddress getRemoteAddress() {
621       return remoteAddress;
622     }
623 
624     @Override
625     public VersionInfo getClientVersionInfo() {
626       return connection.getVersionInfo();
627     }
628 
629     @Override
630     public boolean isRetryImmediatelySupported() {
631       return retryImmediatelySupported;
632     }
633   }
634 
635   /** Listens on the socket. Creates jobs for the handler threads*/
636   private class Listener extends Thread {
637 
638     private ServerSocketChannel acceptChannel = null; //the accept channel
639     private Selector selector = null; //the selector that we use for the server
640     private Reader[] readers = null;
641     private int currentReader = 0;
642     private Random rand = new Random();
643     private long lastCleanupRunTime = 0; //the last time when a cleanup connec-
644                                          //-tion (for idle connections) ran
645     private long cleanupInterval = 10000; //the minimum interval between
646                                           //two cleanup runs
647     private int backlogLength;
648 
649     private ExecutorService readPool;
650 
651     public Listener(final String name) throws IOException {
652       super(name);
653       backlogLength = conf.getInt("hbase.ipc.server.listen.queue.size", 128);
654       // Create a new server socket and set to non blocking mode
655       acceptChannel = ServerSocketChannel.open();
656       acceptChannel.configureBlocking(false);
657 
658       // Bind the server socket to the binding addrees (can be different from the default interface)
659       bind(acceptChannel.socket(), bindAddress, backlogLength);
660       port = acceptChannel.socket().getLocalPort(); //Could be an ephemeral port
661       address = (InetSocketAddress)acceptChannel.socket().getLocalSocketAddress();
662 
663       // create a selector;
664       selector= Selector.open();
665 
666       readers = new Reader[readThreads];
667       readPool = Executors.newFixedThreadPool(readThreads,
668         new ThreadFactoryBuilder().setNameFormat(
669           "RpcServer.reader=%d,bindAddress=" + bindAddress.getHostName() +
670           ",port=" + port).setDaemon(true)
671         .setUncaughtExceptionHandler(Threads.LOGGING_EXCEPTION_HANDLER).build());
672       for (int i = 0; i < readThreads; ++i) {
673         Reader reader = new Reader();
674         readers[i] = reader;
675         readPool.execute(reader);
676       }
677       LOG.info(getName() + ": started " + readThreads + " reader(s) listening on port=" + port);
678 
679       // Register accepts on the server socket with the selector.
680       acceptChannel.register(selector, SelectionKey.OP_ACCEPT);
681       this.setName("RpcServer.listener,port=" + port);
682       this.setDaemon(true);
683     }
684 
685 
686     private class Reader implements Runnable {
687       private volatile boolean adding = false;
688       private final Selector readSelector;
689 
690       Reader() throws IOException {
691         this.readSelector = Selector.open();
692       }
693       @Override
694       public void run() {
695         try {
696           doRunLoop();
697         } finally {
698           try {
699             readSelector.close();
700           } catch (IOException ioe) {
701             LOG.error(getName() + ": error closing read selector in " + getName(), ioe);
702           }
703         }
704       }
705 
706       private synchronized void doRunLoop() {
707         while (running) {
708           try {
709             readSelector.select();
710             while (adding) {
711               this.wait(1000);
712             }
713 
714             Iterator<SelectionKey> iter = readSelector.selectedKeys().iterator();
715             while (iter.hasNext()) {
716               SelectionKey key = iter.next();
717               iter.remove();
718               if (key.isValid()) {
719                 if (key.isReadable()) {
720                   doRead(key);
721                 }
722               }
723             }
724           } catch (InterruptedException e) {
725             LOG.debug("Interrupted while sleeping");
726           } catch (CancelledKeyException e) {
727             LOG.error(getName() + ": CancelledKeyException in Reader", e);
728           } catch (IOException ex) {
729             LOG.info(getName() + ": IOException in Reader", ex);
730           }
731         }
732       }
733 
734       /**
735        * This gets reader into the state that waits for the new channel
736        * to be registered with readSelector. If it was waiting in select()
737        * the thread will be woken up, otherwise whenever select() is called
738        * it will return even if there is nothing to read and wait
739        * in while(adding) for finishAdd call
740        */
741       public void startAdd() {
742         adding = true;
743         readSelector.wakeup();
744       }
745 
746       public synchronized SelectionKey registerChannel(SocketChannel channel)
747         throws IOException {
748         return channel.register(readSelector, SelectionKey.OP_READ);
749       }
750 
751       public synchronized void finishAdd() {
752         adding = false;
753         this.notify();
754       }
755     }
756 
757     /** cleanup connections from connectionList. Choose a random range
758      * to scan and also have a limit on the number of the connections
759      * that will be cleanedup per run. The criteria for cleanup is the time
760      * for which the connection was idle. If 'force' is true then all
761      * connections will be looked at for the cleanup.
762      * @param force all connections will be looked at for cleanup
763      */
764     private void cleanupConnections(boolean force) {
765       if (force || numConnections > thresholdIdleConnections) {
766         long currentTime = System.currentTimeMillis();
767         if (!force && (currentTime - lastCleanupRunTime) < cleanupInterval) {
768           return;
769         }
770         int start = 0;
771         int end = numConnections - 1;
772         if (!force) {
773           start = rand.nextInt(numConnections);
774           end = rand.nextInt(numConnections);
775           int temp;
776           if (end < start) {
777             temp = start;
778             start = end;
779             end = temp;
780           }
781         }
782         int i = start;
783         int numNuked = 0;
784         while (i <= end) {
785           Connection c;
786           synchronized (connectionList) {
787             try {
788               c = connectionList.get(i);
789             } catch (Exception e) {return;}
790           }
791           if (c.timedOut(currentTime)) {
792             if (LOG.isDebugEnabled())
793               LOG.debug(getName() + ": disconnecting client " + c.getHostAddress());
794             closeConnection(c);
795             numNuked++;
796             end--;
797             //noinspection UnusedAssignment
798             c = null;
799             if (!force && numNuked == maxConnectionsToNuke) break;
800           }
801           else i++;
802         }
803         lastCleanupRunTime = System.currentTimeMillis();
804       }
805     }
806 
807     @Override
808     @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="IS2_INCONSISTENT_SYNC",
809       justification="selector access is not synchronized; seems fine but concerned changing " +
810         "it will have per impact")
811     public void run() {
812       LOG.info(getName() + ": starting");
813       while (running) {
814         SelectionKey key = null;
815         try {
816           selector.select(); // FindBugs IS2_INCONSISTENT_SYNC
817           Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
818           while (iter.hasNext()) {
819             key = iter.next();
820             iter.remove();
821             try {
822               if (key.isValid()) {
823                 if (key.isAcceptable())
824                   doAccept(key);
825               }
826             } catch (IOException ignored) {
827               if (LOG.isTraceEnabled()) LOG.trace("ignored", ignored);
828             }
829             key = null;
830           }
831         } catch (OutOfMemoryError e) {
832           if (errorHandler != null) {
833             if (errorHandler.checkOOME(e)) {
834               LOG.info(getName() + ": exiting on OutOfMemoryError");
835               closeCurrentConnection(key, e);
836               cleanupConnections(true);
837               return;
838             }
839           } else {
840             // we can run out of memory if we have too many threads
841             // log the event and sleep for a minute and give
842             // some thread(s) a chance to finish
843             LOG.warn(getName() + ": OutOfMemoryError in server select", e);
844             closeCurrentConnection(key, e);
845             cleanupConnections(true);
846             try {
847               Thread.sleep(60000);
848             } catch (InterruptedException ex) {
849               LOG.debug("Interrupted while sleeping");
850               return;
851             }
852           }
853         } catch (Exception e) {
854           closeCurrentConnection(key, e);
855         }
856         cleanupConnections(false);
857       }
858 
859       LOG.info(getName() + ": stopping");
860 
861       synchronized (this) {
862         try {
863           acceptChannel.close();
864           selector.close();
865         } catch (IOException ignored) {
866           if (LOG.isTraceEnabled()) LOG.trace("ignored", ignored);
867         }
868 
869         selector= null;
870         acceptChannel= null;
871 
872         // clean up all connections
873         while (!connectionList.isEmpty()) {
874           closeConnection(connectionList.remove(0));
875         }
876       }
877     }
878 
879     private void closeCurrentConnection(SelectionKey key, Throwable e) {
880       if (key != null) {
881         Connection c = (Connection)key.attachment();
882         if (c != null) {
883           if (LOG.isDebugEnabled()) {
884             LOG.debug(getName() + ": disconnecting client " + c.getHostAddress() +
885                 (e != null ? " on error " + e.getMessage() : ""));
886           }
887           closeConnection(c);
888           key.attach(null);
889         }
890       }
891     }
892 
893     InetSocketAddress getAddress() {
894       return address;
895     }
896 
897     void doAccept(SelectionKey key) throws IOException, OutOfMemoryError {
898       Connection c;
899       ServerSocketChannel server = (ServerSocketChannel) key.channel();
900 
901       SocketChannel channel;
902       while ((channel = server.accept()) != null) {
903         try {
904           channel.configureBlocking(false);
905           channel.socket().setTcpNoDelay(tcpNoDelay);
906           channel.socket().setKeepAlive(tcpKeepAlive);
907         } catch (IOException ioe) {
908           channel.close();
909           throw ioe;
910         }
911 
912         Reader reader = getReader();
913         try {
914           reader.startAdd();
915           SelectionKey readKey = reader.registerChannel(channel);
916           c = getConnection(channel, System.currentTimeMillis());
917           readKey.attach(c);
918           synchronized (connectionList) {
919             connectionList.add(numConnections, c);
920             numConnections++;
921           }
922           if (LOG.isDebugEnabled())
923             LOG.debug(getName() + ": connection from " + c.toString() +
924                 "; # active connections: " + numConnections);
925         } finally {
926           reader.finishAdd();
927         }
928       }
929     }
930 
931     void doRead(SelectionKey key) throws InterruptedException {
932       int count;
933       Connection c = (Connection) key.attachment();
934       if (c == null) {
935         return;
936       }
937       c.setLastContact(System.currentTimeMillis());
938       try {
939         count = c.readAndProcess();
940 
941         if (count > 0) {
942           c.setLastContact(System.currentTimeMillis());
943         }
944 
945       } catch (InterruptedException ieo) {
946         throw ieo;
947       } catch (Exception e) {
948         if (LOG.isDebugEnabled()) {
949           LOG.debug(getName() + ": Caught exception while reading:", e);
950         }
951         count = -1; //so that the (count < 0) block is executed
952       }
953       if (count < 0) {
954         if (LOG.isDebugEnabled()) {
955           LOG.debug(getName() + ": DISCONNECTING client " + c.toString() +
956               " because read count=" + count +
957               ". Number of active connections: " + numConnections);
958         }
959         closeConnection(c);
960       }
961     }
962 
963     synchronized void doStop() {
964       if (selector != null) {
965         selector.wakeup();
966         Thread.yield();
967       }
968       if (acceptChannel != null) {
969         try {
970           acceptChannel.socket().close();
971         } catch (IOException e) {
972           LOG.info(getName() + ": exception in closing listener socket. " + e);
973         }
974       }
975       readPool.shutdownNow();
976     }
977 
978     // The method that will return the next reader to work with
979     // Simplistic implementation of round robin for now
980     Reader getReader() {
981       currentReader = (currentReader + 1) % readers.length;
982       return readers[currentReader];
983     }
984   }
985 
986   // Sends responses of RPC back to clients.
987   protected class Responder extends Thread {
988     private final Selector writeSelector;
989     private final Set<Connection> writingCons =
990         Collections.newSetFromMap(new ConcurrentHashMap<Connection, Boolean>());
991 
992     Responder() throws IOException {
993       this.setName("RpcServer.responder");
994       this.setDaemon(true);
995       this.setUncaughtExceptionHandler(Threads.LOGGING_EXCEPTION_HANDLER);
996       writeSelector = Selector.open(); // create a selector
997     }
998 
999     @Override
1000     public void run() {
1001       LOG.info(getName() + ": starting");
1002       try {
1003         doRunLoop();
1004       } finally {
1005         LOG.info(getName() + ": stopping");
1006         try {
1007           writeSelector.close();
1008         } catch (IOException ioe) {
1009           LOG.error(getName() + ": couldn't close write selector", ioe);
1010         }
1011       }
1012     }
1013 
1014     /**
1015      * Take the list of the connections that want to write, and register them
1016      * in the selector.
1017      */
1018     private void registerWrites() {
1019       Iterator<Connection> it = writingCons.iterator();
1020       while (it.hasNext()) {
1021         Connection c = it.next();
1022         it.remove();
1023         SelectionKey sk = c.channel.keyFor(writeSelector);
1024         try {
1025           if (sk == null) {
1026             try {
1027               c.channel.register(writeSelector, SelectionKey.OP_WRITE, c);
1028             } catch (ClosedChannelException e) {
1029               // ignore: the client went away.
1030               if (LOG.isTraceEnabled()) LOG.trace("ignored", e);
1031             }
1032           } else {
1033             sk.interestOps(SelectionKey.OP_WRITE);
1034           }
1035         } catch (CancelledKeyException e) {
1036           // ignore: the client went away.
1037           if (LOG.isTraceEnabled()) LOG.trace("ignored", e);
1038         }
1039       }
1040     }
1041 
1042     /**
1043      * Add a connection to the list that want to write,
1044      */
1045     public void registerForWrite(Connection c) {
1046       if (writingCons.add(c)) {
1047         writeSelector.wakeup();
1048       }
1049     }
1050 
1051     private void doRunLoop() {
1052       long lastPurgeTime = 0;   // last check for old calls.
1053       while (running) {
1054         try {
1055           registerWrites();
1056           int keyCt = writeSelector.select(purgeTimeout);
1057           if (keyCt == 0) {
1058             continue;
1059           }
1060 
1061           Set<SelectionKey> keys = writeSelector.selectedKeys();
1062           Iterator<SelectionKey> iter = keys.iterator();
1063           while (iter.hasNext()) {
1064             SelectionKey key = iter.next();
1065             iter.remove();
1066             try {
1067               if (key.isValid() && key.isWritable()) {
1068                 doAsyncWrite(key);
1069               }
1070             } catch (IOException e) {
1071               LOG.debug(getName() + ": asyncWrite", e);
1072             }
1073           }
1074 
1075           lastPurgeTime = purge(lastPurgeTime);
1076 
1077         } catch (OutOfMemoryError e) {
1078           if (errorHandler != null) {
1079             if (errorHandler.checkOOME(e)) {
1080               LOG.info(getName() + ": exiting on OutOfMemoryError");
1081               return;
1082             }
1083           } else {
1084             //
1085             // we can run out of memory if we have too many threads
1086             // log the event and sleep for a minute and give
1087             // some thread(s) a chance to finish
1088             //
1089             LOG.warn(getName() + ": OutOfMemoryError in server select", e);
1090             try {
1091               Thread.sleep(60000);
1092             } catch (InterruptedException ex) {
1093               LOG.debug("Interrupted while sleeping");
1094               return;
1095             }
1096           }
1097         } catch (Exception e) {
1098           LOG.warn(getName() + ": exception in Responder " +
1099               StringUtils.stringifyException(e), e);
1100         }
1101       }
1102       LOG.info(getName() + ": stopped");
1103     }
1104 
1105     /**
1106      * If there were some calls that have not been sent out for a
1107      * long time, we close the connection.
1108      * @return the time of the purge.
1109      */
1110     private long purge(long lastPurgeTime) {
1111       long now = System.currentTimeMillis();
1112       if (now < lastPurgeTime + purgeTimeout) {
1113         return lastPurgeTime;
1114       }
1115 
1116       ArrayList<Connection> conWithOldCalls = new ArrayList<Connection>();
1117       // get the list of channels from list of keys.
1118       synchronized (writeSelector.keys()) {
1119         for (SelectionKey key : writeSelector.keys()) {
1120           Connection connection = (Connection) key.attachment();
1121           if (connection == null) {
1122             throw new IllegalStateException("Coding error: SelectionKey key without attachment.");
1123           }
1124           Call call = connection.responseQueue.peekFirst();
1125           if (call != null && now > call.timestamp + purgeTimeout) {
1126             conWithOldCalls.add(call.connection);
1127           }
1128         }
1129       }
1130 
1131       // Seems safer to close the connection outside of the synchronized loop...
1132       for (Connection connection : conWithOldCalls) {
1133         closeConnection(connection);
1134       }
1135 
1136       return now;
1137     }
1138 
1139     private void doAsyncWrite(SelectionKey key) throws IOException {
1140       Connection connection = (Connection) key.attachment();
1141       if (connection == null) {
1142         throw new IOException("doAsyncWrite: no connection");
1143       }
1144       if (key.channel() != connection.channel) {
1145         throw new IOException("doAsyncWrite: bad channel");
1146       }
1147 
1148       if (processAllResponses(connection)) {
1149         try {
1150           // We wrote everything, so we don't need to be told when the socket is ready for
1151           //  write anymore.
1152          key.interestOps(0);
1153         } catch (CancelledKeyException e) {
1154           /* The Listener/reader might have closed the socket.
1155            * We don't explicitly cancel the key, so not sure if this will
1156            * ever fire.
1157            * This warning could be removed.
1158            */
1159           LOG.warn("Exception while changing ops : " + e);
1160         }
1161       }
1162     }
1163 
1164     /**
1165      * Process the response for this call. You need to have the lock on
1166      * {@link org.apache.hadoop.hbase.ipc.RpcServer.Connection#responseWriteLock}
1167      *
1168      * @param call the call
1169      * @return true if we proceed the call fully, false otherwise.
1170      * @throws IOException
1171      */
1172     private boolean processResponse(final Call call) throws IOException {
1173       boolean error = true;
1174       try {
1175         // Send as much data as we can in the non-blocking fashion
1176         long numBytes = channelWrite(call.connection.channel, call.response);
1177         if (numBytes < 0) {
1178           throw new HBaseIOException("Error writing on the socket " +
1179             "for the call:" + call.toShortString());
1180         }
1181         error = false;
1182       } finally {
1183         if (error) {
1184           LOG.debug(getName() + call.toShortString() + ": output error -- closing");
1185           closeConnection(call.connection);
1186         }
1187       }
1188 
1189       if (!call.response.hasRemaining()) {
1190         call.done();
1191         return true;
1192       } else {
1193         return false; // Socket can't take more, we will have to come back.
1194       }
1195     }
1196 
1197     /**
1198      * Process all the responses for this connection
1199      *
1200      * @return true if all the calls were processed or that someone else is doing it.
1201      * false if there * is still some work to do. In this case, we expect the caller to
1202      * delay us.
1203      * @throws IOException
1204      */
1205     private boolean processAllResponses(final Connection connection) throws IOException {
1206       // We want only one writer on the channel for a connection at a time.
1207       connection.responseWriteLock.lock();
1208       try {
1209         for (int i = 0; i < 20; i++) {
1210           // protection if some handlers manage to need all the responder
1211           Call call = connection.responseQueue.pollFirst();
1212           if (call == null) {
1213             return true;
1214           }
1215           if (!processResponse(call)) {
1216             connection.responseQueue.addFirst(call);
1217             return false;
1218           }
1219         }
1220       } finally {
1221         connection.responseWriteLock.unlock();
1222       }
1223 
1224       return connection.responseQueue.isEmpty();
1225     }
1226 
1227     //
1228     // Enqueue a response from the application.
1229     //
1230     void doRespond(Call call) throws IOException {
1231       boolean added = false;
1232 
1233       // If there is already a write in progress, we don't wait. This allows to free the handlers
1234       //  immediately for other tasks.
1235       if (call.connection.responseQueue.isEmpty() && call.connection.responseWriteLock.tryLock()) {
1236         try {
1237           if (call.connection.responseQueue.isEmpty()) {
1238             // If we're alone, we can try to do a direct call to the socket. It's
1239             //  an optimisation to save on context switches and data transfer between cores..
1240             if (processResponse(call)) {
1241               return; // we're done.
1242             }
1243             // Too big to fit, putting ahead.
1244             call.connection.responseQueue.addFirst(call);
1245             added = true; // We will register to the selector later, outside of the lock.
1246           }
1247         } finally {
1248           call.connection.responseWriteLock.unlock();
1249         }
1250       }
1251 
1252       if (!added) {
1253         call.connection.responseQueue.addLast(call);
1254       }
1255       call.responder.registerForWrite(call.connection);
1256 
1257       // set the serve time when the response has to be sent later
1258       call.timestamp = System.currentTimeMillis();
1259     }
1260   }
1261 
1262   /** Reads calls from a connection and queues them for handling. */
1263   @edu.umd.cs.findbugs.annotations.SuppressWarnings(
1264       value="VO_VOLATILE_INCREMENT",
1265       justification="False positive according to http://sourceforge.net/p/findbugs/bugs/1032/")
1266   public class Connection {
1267     // If initial preamble with version and magic has been read or not.
1268     private boolean connectionPreambleRead = false;
1269     // If the connection header has been read or not.
1270     private boolean connectionHeaderRead = false;
1271     protected SocketChannel channel;
1272     private ByteBuffer data;
1273     private ByteBuffer dataLengthBuffer;
1274     private ByteBuffer preambleBuffer;
1275     protected final ConcurrentLinkedDeque<Call> responseQueue = new ConcurrentLinkedDeque<Call>();
1276     private final Lock responseWriteLock = new ReentrantLock();
1277     private Counter rpcCount = new Counter(); // number of outstanding rpcs
1278     private long lastContact;
1279     private InetAddress addr;
1280     protected Socket socket;
1281     // Cache the remote host & port info so that even if the socket is
1282     // disconnected, we can say where it used to connect to.
1283     protected String hostAddress;
1284     protected int remotePort;
1285     ConnectionHeader connectionHeader;
1286 
1287     /**
1288      * Codec the client asked use.
1289      */
1290     private Codec codec;
1291     /**
1292      * Compression codec the client asked us use.
1293      */
1294     private CompressionCodec compressionCodec;
1295     BlockingService service;
1296 
1297     private AuthMethod authMethod;
1298     private boolean saslContextEstablished;
1299     private boolean skipInitialSaslHandshake;
1300     private ByteBuffer unwrappedData;
1301     // When is this set?  FindBugs wants to know!  Says NP
1302     private ByteBuffer unwrappedDataLengthBuffer = ByteBuffer.allocate(4);
1303     boolean useSasl;
1304     SaslServer saslServer;
1305     private boolean useWrap = false;
1306     // Fake 'call' for failed authorization response
1307     private static final int AUTHORIZATION_FAILED_CALLID = -1;
1308     private final Call authFailedCall = new Call(AUTHORIZATION_FAILED_CALLID, null, null, null,
1309         null, null, this, null, 0, null, null, 0);
1310     private ByteArrayOutputStream authFailedResponse =
1311         new ByteArrayOutputStream();
1312     // Fake 'call' for SASL context setup
1313     private static final int SASL_CALLID = -33;
1314     private final Call saslCall = new Call(SASL_CALLID, null, null, null, null, null, this, null,
1315         0, null, null, 0);
1316 
1317     // was authentication allowed with a fallback to simple auth
1318     private boolean authenticatedWithFallback;
1319 
1320     private boolean retryImmediatelySupported = false;
1321 
1322     public UserGroupInformation attemptingUser = null; // user name before auth
1323     protected User user = null;
1324     protected UserGroupInformation ugi = null;
1325 
1326     public Connection(SocketChannel channel, long lastContact) {
1327       this.channel = channel;
1328       this.lastContact = lastContact;
1329       this.data = null;
1330       this.dataLengthBuffer = ByteBuffer.allocate(4);
1331       this.socket = channel.socket();
1332       this.addr = socket.getInetAddress();
1333       if (addr == null) {
1334         this.hostAddress = "*Unknown*";
1335       } else {
1336         this.hostAddress = addr.getHostAddress();
1337       }
1338       this.remotePort = socket.getPort();
1339       if (socketSendBufferSize != 0) {
1340         try {
1341           socket.setSendBufferSize(socketSendBufferSize);
1342         } catch (IOException e) {
1343           LOG.warn("Connection: unable to set socket send buffer size to " +
1344                    socketSendBufferSize);
1345         }
1346       }
1347     }
1348 
1349       @Override
1350     public String toString() {
1351       return getHostAddress() + ":" + remotePort;
1352     }
1353 
1354     public String getHostAddress() {
1355       return hostAddress;
1356     }
1357 
1358     public InetAddress getHostInetAddress() {
1359       return addr;
1360     }
1361 
1362     public int getRemotePort() {
1363       return remotePort;
1364     }
1365 
1366     public void setLastContact(long lastContact) {
1367       this.lastContact = lastContact;
1368     }
1369 
1370     public VersionInfo getVersionInfo() {
1371       if (connectionHeader.hasVersionInfo()) {
1372         return connectionHeader.getVersionInfo();
1373       }
1374       return null;
1375     }
1376 
1377     /* Return true if the connection has no outstanding rpc */
1378     private boolean isIdle() {
1379       return rpcCount.get() == 0;
1380     }
1381 
1382     /* Decrement the outstanding RPC count */
1383     protected void decRpcCount() {
1384       rpcCount.decrement();
1385     }
1386 
1387     /* Increment the outstanding RPC count */
1388     protected void incRpcCount() {
1389       rpcCount.increment();
1390     }
1391 
1392     protected boolean timedOut(long currentTime) {
1393       return isIdle() && currentTime - lastContact > maxIdleTime;
1394     }
1395 
1396     private UserGroupInformation getAuthorizedUgi(String authorizedId)
1397         throws IOException {
1398       UserGroupInformation authorizedUgi;
1399       if (authMethod == AuthMethod.DIGEST) {
1400         TokenIdentifier tokenId = HBaseSaslRpcServer.getIdentifier(authorizedId,
1401             secretManager);
1402         authorizedUgi = tokenId.getUser();
1403         if (authorizedUgi == null) {
1404           throw new AccessDeniedException(
1405               "Can't retrieve username from tokenIdentifier.");
1406         }
1407         authorizedUgi.addTokenIdentifier(tokenId);
1408       } else {
1409         authorizedUgi = UserGroupInformation.createRemoteUser(authorizedId);
1410       }
1411       authorizedUgi.setAuthenticationMethod(authMethod.authenticationMethod.getAuthMethod());
1412       return authorizedUgi;
1413     }
1414 
1415     private void saslReadAndProcess(ByteBuffer saslToken) throws IOException,
1416         InterruptedException {
1417       if (saslContextEstablished) {
1418         if (LOG.isTraceEnabled())
1419           LOG.trace("Have read input token of size " + saslToken.limit()
1420               + " for processing by saslServer.unwrap()");
1421 
1422         if (!useWrap) {
1423           processOneRpc(saslToken);
1424         } else {
1425           byte[] b = saslToken.array();
1426           byte [] plaintextData = saslServer.unwrap(b, saslToken.position(), saslToken.limit());
1427           processUnwrappedData(plaintextData);
1428         }
1429       } else {
1430         byte[] replyToken;
1431         try {
1432           if (saslServer == null) {
1433             switch (authMethod) {
1434             case DIGEST:
1435               if (secretManager == null) {
1436                 throw new AccessDeniedException(
1437                     "Server is not configured to do DIGEST authentication.");
1438               }
1439               saslServer = Sasl.createSaslServer(AuthMethod.DIGEST
1440                   .getMechanismName(), null, SaslUtil.SASL_DEFAULT_REALM,
1441                   HBaseSaslRpcServer.getSaslProps(), new SaslDigestCallbackHandler(
1442                       secretManager, this));
1443               break;
1444             default:
1445               UserGroupInformation current = UserGroupInformation.getCurrentUser();
1446               String fullName = current.getUserName();
1447               if (LOG.isDebugEnabled()) {
1448                 LOG.debug("Kerberos principal name is " + fullName);
1449               }
1450               final String names[] = SaslUtil.splitKerberosName(fullName);
1451               if (names.length != 3) {
1452                 throw new AccessDeniedException(
1453                     "Kerberos principal name does NOT have the expected "
1454                         + "hostname part: " + fullName);
1455               }
1456               current.doAs(new PrivilegedExceptionAction<Object>() {
1457                 @Override
1458                 public Object run() throws SaslException {
1459                   saslServer = Sasl.createSaslServer(AuthMethod.KERBEROS
1460                       .getMechanismName(), names[0], names[1],
1461                       HBaseSaslRpcServer.getSaslProps(), new SaslGssCallbackHandler());
1462                   return null;
1463                 }
1464               });
1465             }
1466             if (saslServer == null)
1467               throw new AccessDeniedException(
1468                   "Unable to find SASL server implementation for "
1469                       + authMethod.getMechanismName());
1470             if (LOG.isDebugEnabled()) {
1471               LOG.debug("Created SASL server with mechanism = " + authMethod.getMechanismName());
1472             }
1473           }
1474           if (LOG.isDebugEnabled()) {
1475             LOG.debug("Have read input token of size " + saslToken.limit()
1476                 + " for processing by saslServer.evaluateResponse()");
1477           }
1478           replyToken = saslServer.evaluateResponse(saslToken.array());
1479         } catch (IOException e) {
1480           IOException sendToClient = e;
1481           Throwable cause = e;
1482           while (cause != null) {
1483             if (cause instanceof InvalidToken) {
1484               sendToClient = (InvalidToken) cause;
1485               break;
1486             }
1487             cause = cause.getCause();
1488           }
1489           doRawSaslReply(SaslStatus.ERROR, null, sendToClient.getClass().getName(),
1490             sendToClient.getLocalizedMessage());
1491           metrics.authenticationFailure();
1492           String clientIP = this.toString();
1493           // attempting user could be null
1494           AUDITLOG.warn(AUTH_FAILED_FOR + clientIP + ":" + attemptingUser);
1495           throw e;
1496         }
1497         if (replyToken != null) {
1498           if (LOG.isDebugEnabled()) {
1499             LOG.debug("Will send token of size " + replyToken.length
1500                 + " from saslServer.");
1501           }
1502           doRawSaslReply(SaslStatus.SUCCESS, new BytesWritable(replyToken), null,
1503               null);
1504         }
1505         if (saslServer.isComplete()) {
1506           String qop = (String) saslServer.getNegotiatedProperty(Sasl.QOP);
1507           useWrap = qop != null && !"auth".equalsIgnoreCase(qop);
1508           ugi = getAuthorizedUgi(saslServer.getAuthorizationID());
1509           if (LOG.isDebugEnabled()) {
1510             LOG.debug("SASL server context established. Authenticated client: "
1511               + ugi + ". Negotiated QoP is "
1512               + saslServer.getNegotiatedProperty(Sasl.QOP));
1513           }
1514           metrics.authenticationSuccess();
1515           AUDITLOG.info(AUTH_SUCCESSFUL_FOR + ugi);
1516           saslContextEstablished = true;
1517         }
1518       }
1519     }
1520 
1521     /**
1522      * No protobuf encoding of raw sasl messages
1523      */
1524     private void doRawSaslReply(SaslStatus status, Writable rv,
1525         String errorClass, String error) throws IOException {
1526       ByteBufferOutputStream saslResponse = null;
1527       DataOutputStream out = null;
1528       try {
1529         // In my testing, have noticed that sasl messages are usually
1530         // in the ballpark of 100-200. That's why the initial capacity is 256.
1531         saslResponse = new ByteBufferOutputStream(256);
1532         out = new DataOutputStream(saslResponse);
1533         out.writeInt(status.state); // write status
1534         if (status == SaslStatus.SUCCESS) {
1535           rv.write(out);
1536         } else {
1537           WritableUtils.writeString(out, errorClass);
1538           WritableUtils.writeString(out, error);
1539         }
1540         saslCall.setSaslTokenResponse(saslResponse.getByteBuffer());
1541         saslCall.responder = responder;
1542         saslCall.sendResponseIfReady();
1543       } finally {
1544         if (saslResponse != null) {
1545           saslResponse.close();
1546         }
1547         if (out != null) {
1548           out.close();
1549         }
1550       }
1551     }
1552 
1553     private void disposeSasl() {
1554       if (saslServer != null) {
1555         try {
1556           saslServer.dispose();
1557           saslServer = null;
1558         } catch (SaslException ignored) {
1559           // Ignored. This is being disposed of anyway.
1560         }
1561       }
1562     }
1563 
1564     private int readPreamble() throws IOException {
1565       if (preambleBuffer == null) {
1566         preambleBuffer = ByteBuffer.allocate(6);
1567       }
1568       int count = channelRead(channel, preambleBuffer);
1569       if (count < 0 || preambleBuffer.remaining() > 0) {
1570         return count;
1571       }
1572       // Check for 'HBas' magic.
1573       preambleBuffer.flip();
1574       for (int i = 0; i < HConstants.RPC_HEADER.length; i++) {
1575         if (HConstants.RPC_HEADER[i] != preambleBuffer.get(i)) {
1576           return doBadPreambleHandling("Expected HEADER=" +
1577               Bytes.toStringBinary(HConstants.RPC_HEADER) + " but received HEADER=" +
1578               Bytes.toStringBinary(preambleBuffer.array(), 0, HConstants.RPC_HEADER.length) +
1579               " from " + toString());
1580         }
1581       }
1582       int version = preambleBuffer.get(HConstants.RPC_HEADER.length);
1583       byte authbyte = preambleBuffer.get(HConstants.RPC_HEADER.length + 1);
1584       this.authMethod = AuthMethod.valueOf(authbyte);
1585       if (version != CURRENT_VERSION) {
1586         String msg = getFatalConnectionString(version, authbyte);
1587         return doBadPreambleHandling(msg, new WrongVersionException(msg));
1588       }
1589       if (authMethod == null) {
1590         String msg = getFatalConnectionString(version, authbyte);
1591         return doBadPreambleHandling(msg, new BadAuthException(msg));
1592       }
1593       if (isSecurityEnabled && authMethod == AuthMethod.SIMPLE) {
1594         if (allowFallbackToSimpleAuth) {
1595           metrics.authenticationFallback();
1596           authenticatedWithFallback = true;
1597         } else {
1598           AccessDeniedException ae = new AccessDeniedException("Authentication is required");
1599           setupResponse(authFailedResponse, authFailedCall, ae, ae.getMessage());
1600           responder.doRespond(authFailedCall);
1601           throw ae;
1602         }
1603       }
1604       if (!isSecurityEnabled && authMethod != AuthMethod.SIMPLE) {
1605         doRawSaslReply(SaslStatus.SUCCESS, new IntWritable(
1606             SaslUtil.SWITCH_TO_SIMPLE_AUTH), null, null);
1607         authMethod = AuthMethod.SIMPLE;
1608         // client has already sent the initial Sasl message and we
1609         // should ignore it. Both client and server should fall back
1610         // to simple auth from now on.
1611         skipInitialSaslHandshake = true;
1612       }
1613       if (authMethod != AuthMethod.SIMPLE) {
1614         useSasl = true;
1615       }
1616 
1617       preambleBuffer = null; // do not need it anymore
1618       connectionPreambleRead = true;
1619       return count;
1620     }
1621 
1622     private int read4Bytes() throws IOException {
1623       if (this.dataLengthBuffer.remaining() > 0) {
1624         return channelRead(channel, this.dataLengthBuffer);
1625       } else {
1626         return 0;
1627       }
1628     }
1629 
1630 
1631     /**
1632      * Read off the wire. If there is not enough data to read, update the connection state with
1633      *  what we have and returns.
1634      * @return Returns -1 if failure (and caller will close connection), else zero or more.
1635      * @throws IOException
1636      * @throws InterruptedException
1637      */
1638     public int readAndProcess() throws IOException, InterruptedException {
1639       // If we have not read the connection setup preamble, look to see if that is on the wire.
1640       if (!connectionPreambleRead) {
1641         int count = readPreamble();
1642         if (!connectionPreambleRead) {
1643           return count;
1644         }
1645       }
1646       // Try and read in an int. It will be length of the data to read (or -1 if a ping). We catch
1647       // the integer length into the 4-byte this.dataLengthBuffer.
1648       int count = read4Bytes();
1649       if (count < 0 || dataLengthBuffer.remaining() > 0) {
1650         return count;
1651       }
1652 
1653       // If we have not read the connection setup preamble, look to see if that is on the wire.
1654       if (!connectionPreambleRead) {
1655         count = readPreamble();
1656         if (!connectionPreambleRead) {
1657           return count;
1658         }
1659 
1660         count = read4Bytes();
1661         if (count < 0 || dataLengthBuffer.remaining() > 0) {
1662           return count;
1663         }
1664       }
1665 
1666       // We have read a length and we have read the preamble.  It is either the connection header
1667       // or it is a request.
1668       if (data == null) {
1669         dataLengthBuffer.flip();
1670         int dataLength = dataLengthBuffer.getInt();
1671         if (dataLength == RpcClient.PING_CALL_ID) {
1672           if (!useWrap) { //covers the !useSasl too
1673             dataLengthBuffer.clear();
1674             return 0;  //ping message
1675           }
1676         }
1677         if (dataLength < 0) { // A data length of zero is legal.
1678           throw new DoNotRetryIOException("Unexpected data length "
1679               + dataLength + "!! from " + getHostAddress());
1680         }
1681 
1682         if (dataLength > maxRequestSize) {
1683           String msg = "RPC data length of " + dataLength + " received from "
1684               + getHostAddress() + " is greater than max allowed "
1685               + maxRequestSize + ". Set \"" + MAX_REQUEST_SIZE
1686               + "\" on server to override this limit (not recommended)";
1687           LOG.warn(msg);
1688 
1689           if (connectionHeaderRead && connectionPreambleRead) {
1690             incRpcCount();
1691             // Construct InputStream for the non-blocking SocketChannel
1692             // We need the InputStream because we want to read only the request header
1693             // instead of the whole rpc.
1694             final ByteBuffer buf = ByteBuffer.allocate(1);
1695             InputStream is = new InputStream() {
1696               @Override
1697               public int read() throws IOException {
1698                 channelRead(channel, buf);
1699                 buf.flip();
1700                 int x = buf.get();
1701                 buf.flip();
1702                 return x;
1703               }
1704             };
1705             CodedInputStream cis = CodedInputStream.newInstance(is);
1706             int headerSize = cis.readRawVarint32();
1707             Message.Builder builder = RequestHeader.newBuilder();
1708             ProtobufUtil.mergeFrom(builder, cis, headerSize);
1709             RequestHeader header = (RequestHeader) builder.build();
1710 
1711             // Notify the client about the offending request
1712             Call reqTooBig = new Call(header.getCallId(), this.service, null, null, null,
1713                 null, this, responder, 0, null, this.addr,0);
1714             metrics.exception(REQUEST_TOO_BIG_EXCEPTION);
1715             // Make sure the client recognizes the underlying exception
1716             // Otherwise, throw a DoNotRetryIOException.
1717             if (VersionInfoUtil.hasMinimumVersion(connectionHeader.getVersionInfo(),
1718                 RequestTooBigException.MAJOR_VERSION, RequestTooBigException.MINOR_VERSION)) {
1719               setupResponse(null, reqTooBig, REQUEST_TOO_BIG_EXCEPTION, msg);
1720             } else {
1721               setupResponse(null, reqTooBig, new DoNotRetryIOException(), msg);
1722             }
1723             // We are going to close the connection, make sure we process the response
1724             // before that. In rare case when this fails, we still close the connection.
1725             responseWriteLock.lock();
1726             responder.processResponse(reqTooBig);
1727             responseWriteLock.unlock();
1728           }
1729           // Close the connection
1730           return -1;
1731         }
1732 
1733         data = ByteBuffer.allocate(dataLength);
1734 
1735         // Increment the rpc count. This counter will be decreased when we write
1736         //  the response.  If we want the connection to be detected as idle properly, we
1737         //  need to keep the inc / dec correct.
1738         incRpcCount();
1739       }
1740 
1741       count = channelRead(channel, data);
1742 
1743       if (count >= 0 && data.remaining() == 0) { // count==0 if dataLength == 0
1744         process();
1745       }
1746 
1747       return count;
1748     }
1749 
1750     /**
1751      * Process the data buffer and clean the connection state for the next call.
1752      */
1753     private void process() throws IOException, InterruptedException {
1754       data.flip();
1755       try {
1756         if (skipInitialSaslHandshake) {
1757           skipInitialSaslHandshake = false;
1758           return;
1759         }
1760 
1761         if (useSasl) {
1762           saslReadAndProcess(data);
1763         } else {
1764           processOneRpc(data);
1765         }
1766 
1767       } finally {
1768         dataLengthBuffer.clear(); // Clean for the next call
1769         data = null; // For the GC
1770       }
1771     }
1772 
1773     private String getFatalConnectionString(final int version, final byte authByte) {
1774       return "serverVersion=" + CURRENT_VERSION +
1775       ", clientVersion=" + version + ", authMethod=" + authByte +
1776       ", authSupported=" + (authMethod != null) + " from " + toString();
1777     }
1778 
1779     private int doBadPreambleHandling(final String msg) throws IOException {
1780       return doBadPreambleHandling(msg, new FatalConnectionException(msg));
1781     }
1782 
1783     private int doBadPreambleHandling(final String msg, final Exception e) throws IOException {
1784       LOG.warn(msg);
1785       Call fakeCall = new Call(-1, null, null, null, null, null, this, responder, -1, null, null,0);
1786       setupResponse(null, fakeCall, e, msg);
1787       responder.doRespond(fakeCall);
1788       // Returning -1 closes out the connection.
1789       return -1;
1790     }
1791 
1792     // Reads the connection header following version
1793     private void processConnectionHeader(ByteBuffer buf) throws IOException {
1794       this.connectionHeader = ConnectionHeader.parseFrom(
1795         new ByteBufferInputStream(buf));
1796       String serviceName = connectionHeader.getServiceName();
1797       if (serviceName == null) throw new EmptyServiceNameException();
1798       this.service = getService(services, serviceName);
1799       if (this.service == null) throw new UnknownServiceException(serviceName);
1800       setupCellBlockCodecs(this.connectionHeader);
1801       UserGroupInformation protocolUser = createUser(connectionHeader);
1802       if (!useSasl) {
1803         ugi = protocolUser;
1804         if (ugi != null) {
1805           ugi.setAuthenticationMethod(AuthMethod.SIMPLE.authenticationMethod);
1806         }
1807         // audit logging for SASL authenticated users happens in saslReadAndProcess()
1808         if (authenticatedWithFallback) {
1809           LOG.warn("Allowed fallback to SIMPLE auth for " + ugi
1810               + " connecting from " + getHostAddress());
1811         }
1812         AUDITLOG.info(AUTH_SUCCESSFUL_FOR + ugi);
1813       } else {
1814         // user is authenticated
1815         ugi.setAuthenticationMethod(authMethod.authenticationMethod);
1816         //Now we check if this is a proxy user case. If the protocol user is
1817         //different from the 'user', it is a proxy user scenario. However,
1818         //this is not allowed if user authenticated with DIGEST.
1819         if ((protocolUser != null)
1820             && (!protocolUser.getUserName().equals(ugi.getUserName()))) {
1821           if (authMethod == AuthMethod.DIGEST) {
1822             // Not allowed to doAs if token authentication is used
1823             throw new AccessDeniedException("Authenticated user (" + ugi
1824                 + ") doesn't match what the client claims to be ("
1825                 + protocolUser + ")");
1826           } else {
1827             // Effective user can be different from authenticated user
1828             // for simple auth or kerberos auth
1829             // The user is the real user. Now we create a proxy user
1830             UserGroupInformation realUser = ugi;
1831             ugi = UserGroupInformation.createProxyUser(protocolUser
1832                 .getUserName(), realUser);
1833             // Now the user is a proxy user, set Authentication method Proxy.
1834             ugi.setAuthenticationMethod(AuthenticationMethod.PROXY);
1835           }
1836         }
1837       }
1838       if (connectionHeader.hasVersionInfo()) {
1839         // see if this connection will support RetryImmediatelyException
1840         retryImmediatelySupported = VersionInfoUtil.hasMinimumVersion(getVersionInfo(), 1, 2);
1841 
1842         AUDITLOG.info("Connection from " + this.hostAddress + " port: " + this.remotePort
1843             + " with version info: "
1844             + TextFormat.shortDebugString(connectionHeader.getVersionInfo()));
1845       } else {
1846         AUDITLOG.info("Connection from " + this.hostAddress + " port: " + this.remotePort
1847             + " with unknown version info");
1848       }
1849 
1850 
1851     }
1852 
1853     /**
1854      * Set up cell block codecs
1855      * @throws FatalConnectionException
1856      */
1857     private void setupCellBlockCodecs(final ConnectionHeader header)
1858     throws FatalConnectionException {
1859       // TODO: Plug in other supported decoders.
1860       if (!header.hasCellBlockCodecClass()) return;
1861       String className = header.getCellBlockCodecClass();
1862       if (className == null || className.length() == 0) return;
1863       try {
1864         this.codec = (Codec)Class.forName(className).getDeclaredConstructor().newInstance();
1865       } catch (Exception e) {
1866         throw new UnsupportedCellCodecException(className, e);
1867       }
1868       if (!header.hasCellBlockCompressorClass()) return;
1869       className = header.getCellBlockCompressorClass();
1870       try {
1871         this.compressionCodec = (CompressionCodec)
1872           Class.forName(className).getDeclaredConstructor().newInstance();
1873       } catch (Exception e) {
1874         throw new UnsupportedCompressionCodecException(className, e);
1875       }
1876     }
1877 
1878     private void processUnwrappedData(byte[] inBuf) throws IOException,
1879     InterruptedException {
1880       ReadableByteChannel ch = Channels.newChannel(new ByteArrayInputStream(inBuf));
1881       // Read all RPCs contained in the inBuf, even partial ones
1882       while (true) {
1883         int count;
1884         if (unwrappedDataLengthBuffer.remaining() > 0) {
1885           count = channelRead(ch, unwrappedDataLengthBuffer);
1886           if (count <= 0 || unwrappedDataLengthBuffer.remaining() > 0)
1887             return;
1888         }
1889 
1890         if (unwrappedData == null) {
1891           unwrappedDataLengthBuffer.flip();
1892           int unwrappedDataLength = unwrappedDataLengthBuffer.getInt();
1893 
1894           if (unwrappedDataLength == RpcClient.PING_CALL_ID) {
1895             if (LOG.isDebugEnabled())
1896               LOG.debug("Received ping message");
1897             unwrappedDataLengthBuffer.clear();
1898             continue; // ping message
1899           }
1900           unwrappedData = ByteBuffer.allocate(unwrappedDataLength);
1901         }
1902 
1903         count = channelRead(ch, unwrappedData);
1904         if (count <= 0 || unwrappedData.remaining() > 0)
1905           return;
1906 
1907         if (unwrappedData.remaining() == 0) {
1908           unwrappedDataLengthBuffer.clear();
1909           unwrappedData.flip();
1910           processOneRpc(unwrappedData);
1911           unwrappedData = null;
1912         }
1913       }
1914     }
1915 
1916 
1917     private void processOneRpc(ByteBuffer buf) throws IOException, InterruptedException {
1918       if (connectionHeaderRead) {
1919         processRequest(buf);
1920       } else {
1921         processConnectionHeader(buf);
1922         this.connectionHeaderRead = true;
1923         if (!authorizeConnection()) {
1924           // Throw FatalConnectionException wrapping ACE so client does right thing and closes
1925           // down the connection instead of trying to read non-existent retun.
1926           throw new AccessDeniedException("Connection from " + this + " for service " +
1927             connectionHeader.getServiceName() + " is unauthorized for user: " + ugi);
1928         }
1929         this.user = userProvider.create(this.ugi);
1930       }
1931     }
1932 
1933     /**
1934      * @param buf Has the request header and the request param and optionally encoded data buffer
1935      * all in this one array.
1936      * @throws IOException
1937      * @throws InterruptedException
1938      */
1939     protected void processRequest(ByteBuffer buf) throws IOException, InterruptedException {
1940       long totalRequestSize = buf.limit();
1941       int offset = 0;
1942       // Here we read in the header.  We avoid having pb
1943       // do its default 4k allocation for CodedInputStream.  We force it to use backing array.
1944       CodedInputStream cis = CodedInputStream.newInstance(buf.array(), offset, buf.limit());
1945       int headerSize = cis.readRawVarint32();
1946       offset = cis.getTotalBytesRead();
1947       Message.Builder builder = RequestHeader.newBuilder();
1948       ProtobufUtil.mergeFrom(builder, cis, headerSize);
1949       RequestHeader header = (RequestHeader) builder.build();
1950       offset += headerSize;
1951       int id = header.getCallId();
1952       if (LOG.isTraceEnabled()) {
1953         LOG.trace("RequestHeader " + TextFormat.shortDebugString(header) +
1954           " totalRequestSize: " + totalRequestSize + " bytes");
1955       }
1956       // Enforcing the call queue size, this triggers a retry in the client
1957       // This is a bit late to be doing this check - we have already read in the total request.
1958       if ((totalRequestSize + callQueueSize.get()) > maxQueueSize) {
1959         final Call callTooBig =
1960           new Call(id, this.service, null, null, null, null, this,
1961             responder, totalRequestSize, null, null, 0);
1962         ByteArrayOutputStream responseBuffer = new ByteArrayOutputStream();
1963         metrics.exception(CALL_QUEUE_TOO_BIG_EXCEPTION);
1964         setupResponse(responseBuffer, callTooBig, CALL_QUEUE_TOO_BIG_EXCEPTION,
1965             "Call queue is full on " + server.getServerName() +
1966                 ", is hbase.ipc.server.max.callqueue.size too small?");
1967         responder.doRespond(callTooBig);
1968         return;
1969       }
1970       MethodDescriptor md = null;
1971       Message param = null;
1972       CellScanner cellScanner = null;
1973       try {
1974         if (header.hasRequestParam() && header.getRequestParam()) {
1975           md = this.service.getDescriptorForType().findMethodByName(header.getMethodName());
1976           if (md == null) throw new UnsupportedOperationException(header.getMethodName());
1977           builder = this.service.getRequestPrototype(md).newBuilderForType();
1978           cis.resetSizeCounter();
1979           int paramSize = cis.readRawVarint32();
1980           offset += cis.getTotalBytesRead();
1981           if (builder != null) {
1982             ProtobufUtil.mergeFrom(builder, cis, paramSize);
1983             param = builder.build();
1984           }
1985           offset += paramSize;
1986         } else {
1987           // currently header must have request param, so we directly throw exception here
1988           String msg = "Invalid request header: " + TextFormat.shortDebugString(header)
1989               + ", should have param set in it";
1990           LOG.warn(msg);
1991           throw new DoNotRetryIOException(msg);
1992         }
1993         if (header.hasCellBlockMeta()) {
1994           buf.position(offset);
1995           cellScanner = cellBlockBuilder.createCellScanner(this.codec, this.compressionCodec, buf);
1996         }
1997       } catch (Throwable t) {
1998         InetSocketAddress address = getListenerAddress();
1999         String msg = (address != null ? address : "(channel closed)") +
2000             " is unable to read call parameter from client " + getHostAddress();
2001         LOG.warn(msg, t);
2002 
2003         metrics.exception(t);
2004 
2005         // probably the hbase hadoop version does not match the running hadoop version
2006         if (t instanceof LinkageError) {
2007           t = new DoNotRetryIOException(t);
2008         }
2009         // If the method is not present on the server, do not retry.
2010         if (t instanceof UnsupportedOperationException) {
2011           t = new DoNotRetryIOException(t);
2012         }
2013 
2014         final Call readParamsFailedCall =
2015           new Call(id, this.service, null, null, null, null, this,
2016             responder, totalRequestSize, null, null, 0);
2017         ByteArrayOutputStream responseBuffer = new ByteArrayOutputStream();
2018         setupResponse(responseBuffer, readParamsFailedCall, t,
2019           msg + "; " + t.getMessage());
2020         responder.doRespond(readParamsFailedCall);
2021         return;
2022       }
2023 
2024       TraceInfo traceInfo = header.hasTraceInfo()
2025           ? new TraceInfo(header.getTraceInfo().getTraceId(), header.getTraceInfo().getParentId())
2026           : null;
2027       int timeout = 0;
2028       if (header.hasTimeout() && header.getTimeout() > 0){
2029         timeout = Math.max(minClientRequestTimeout, header.getTimeout());
2030       }
2031       Call call = new Call(id, this.service, md, header, param, cellScanner, this, responder,
2032               totalRequestSize, traceInfo, this.addr, timeout);
2033 
2034       if (!scheduler.dispatch(new CallRunner(RpcServer.this, call))) {
2035         callQueueSize.add(-1 * call.getSize());
2036 
2037         ByteArrayOutputStream responseBuffer = new ByteArrayOutputStream();
2038         metrics.exception(CALL_QUEUE_TOO_BIG_EXCEPTION);
2039         setupResponse(responseBuffer, call, CALL_QUEUE_TOO_BIG_EXCEPTION,
2040             "Call queue is full on " + server.getServerName() +
2041                 ", too many items queued ?");
2042         responder.doRespond(call);
2043       }
2044     }
2045 
2046     private boolean authorizeConnection() throws IOException {
2047       try {
2048         // If auth method is DIGEST, the token was obtained by the
2049         // real user for the effective user, therefore not required to
2050         // authorize real user. doAs is allowed only for simple or kerberos
2051         // authentication
2052         if (ugi != null && ugi.getRealUser() != null
2053             && (authMethod != AuthMethod.DIGEST)) {
2054           ProxyUsers.authorize(ugi, this.getHostAddress(), conf);
2055         }
2056         authorize(ugi, connectionHeader, getHostInetAddress());
2057         metrics.authorizationSuccess();
2058       } catch (AuthorizationException ae) {
2059         if (LOG.isDebugEnabled()) {
2060           LOG.debug("Connection authorization failed: " + ae.getMessage(), ae);
2061         }
2062         metrics.authorizationFailure();
2063         setupResponse(authFailedResponse, authFailedCall,
2064           new AccessDeniedException(ae), ae.getMessage());
2065         responder.doRespond(authFailedCall);
2066         return false;
2067       }
2068       return true;
2069     }
2070 
2071     protected synchronized void close() {
2072       disposeSasl();
2073       data = null;
2074       if (!channel.isOpen())
2075         return;
2076       try {socket.shutdownOutput();} catch(Exception ignored) {
2077         if (LOG.isTraceEnabled()) {
2078           LOG.trace(ignored);
2079         }
2080       }
2081       if (channel.isOpen()) {
2082         try {channel.close();} catch(Exception ignored) {
2083           if (LOG.isTraceEnabled()) {
2084             LOG.trace(ignored);
2085           }
2086         }
2087       }
2088       try {socket.close();} catch(Exception ignored) {
2089         if (LOG.isTraceEnabled()) {
2090           LOG.trace(ignored);
2091         }
2092       }
2093     }
2094 
2095     private UserGroupInformation createUser(ConnectionHeader head) {
2096       UserGroupInformation ugi = null;
2097 
2098       if (!head.hasUserInfo()) {
2099         return null;
2100       }
2101       UserInformation userInfoProto = head.getUserInfo();
2102       String effectiveUser = null;
2103       if (userInfoProto.hasEffectiveUser()) {
2104         effectiveUser = userInfoProto.getEffectiveUser();
2105       }
2106       String realUser = null;
2107       if (userInfoProto.hasRealUser()) {
2108         realUser = userInfoProto.getRealUser();
2109       }
2110       if (effectiveUser != null) {
2111         if (realUser != null) {
2112           UserGroupInformation realUserUgi =
2113               UserGroupInformation.createRemoteUser(realUser);
2114           ugi = UserGroupInformation.createProxyUser(effectiveUser, realUserUgi);
2115         } else {
2116           ugi = UserGroupInformation.createRemoteUser(effectiveUser);
2117         }
2118       }
2119       return ugi;
2120     }
2121   }
2122 
2123   /**
2124    * Datastructure for passing a {@link BlockingService} and its associated class of
2125    * protobuf service interface.  For example, a server that fielded what is defined
2126    * in the client protobuf service would pass in an implementation of the client blocking service
2127    * and then its ClientService.BlockingInterface.class.  Used checking connection setup.
2128    */
2129   public static class BlockingServiceAndInterface {
2130     private final BlockingService service;
2131     private final Class<?> serviceInterface;
2132     public BlockingServiceAndInterface(final BlockingService service,
2133         final Class<?> serviceInterface) {
2134       this.service = service;
2135       this.serviceInterface = serviceInterface;
2136     }
2137     public Class<?> getServiceInterface() {
2138       return this.serviceInterface;
2139     }
2140     public BlockingService getBlockingService() {
2141       return this.service;
2142     }
2143   }
2144 
2145   /**
2146    * Constructs a server listening on the named port and address.
2147    * @param server hosting instance of {@link Server}. We will do authentications if an
2148    * instance else pass null for no authentication check.
2149    * @param name Used keying this rpc servers' metrics and for naming the Listener thread.
2150    * @param services A list of services.
2151    * @param bindAddress Where to listen
2152    * @param conf
2153    * @param scheduler
2154    */
2155   public RpcServer(final Server server, final String name,
2156       final List<BlockingServiceAndInterface> services,
2157       final InetSocketAddress bindAddress, Configuration conf,
2158       RpcScheduler scheduler)
2159       throws IOException {
2160     
2161     if (conf.getBoolean("hbase.ipc.server.reservoir.enabled", true)) {
2162       this.reservoir = new BoundedByteBufferPool(
2163           conf.getInt("hbase.ipc.server.reservoir.max.buffer.size", 1024 * 1024),
2164           conf.getInt("hbase.ipc.server.reservoir.initial.buffer.size", 16 * 1024),
2165           // Make the max twice the number of handlers to be safe.
2166           conf.getInt("hbase.ipc.server.reservoir.initial.max",
2167               conf.getInt(HConstants.REGION_SERVER_HANDLER_COUNT,
2168                   HConstants.DEFAULT_REGION_SERVER_HANDLER_COUNT) * 2),
2169           // By default make direct byte buffers from the buffer pool.
2170           conf.getBoolean("hbase.ipc.server.reservoir.direct.buffer", true));
2171     } else {
2172       reservoir = null;
2173     }
2174     this.server = server;
2175     this.services = services;
2176     this.bindAddress = bindAddress;
2177     this.conf = conf;
2178     this.socketSendBufferSize = 0;
2179     this.maxQueueSize =
2180       this.conf.getInt("hbase.ipc.server.max.callqueue.size", DEFAULT_MAX_CALLQUEUE_SIZE);
2181     this.readThreads = conf.getInt("hbase.ipc.server.read.threadpool.size", 10);
2182     this.maxIdleTime = 2 * conf.getInt("hbase.ipc.client.connection.maxidletime", 1000);
2183     this.maxConnectionsToNuke = conf.getInt("hbase.ipc.client.kill.max", 10);
2184     this.thresholdIdleConnections = conf.getInt("hbase.ipc.client.idlethreshold", 4000);
2185     this.purgeTimeout = conf.getLong("hbase.ipc.client.call.purge.timeout",
2186       2 * HConstants.DEFAULT_HBASE_RPC_TIMEOUT);
2187     this.warnResponseTime = conf.getInt(WARN_RESPONSE_TIME, DEFAULT_WARN_RESPONSE_TIME);
2188     this.warnResponseSize = conf.getInt(WARN_RESPONSE_SIZE, DEFAULT_WARN_RESPONSE_SIZE);
2189     this.minClientRequestTimeout = conf.getInt(MIN_CLIENT_REQUEST_TIMEOUT,
2190         DEFAULT_MIN_CLIENT_REQUEST_TIMEOUT);
2191     this.maxRequestSize = conf.getInt(MAX_REQUEST_SIZE, DEFAULT_MAX_REQUEST_SIZE);
2192 
2193     // Start the listener here and let it bind to the port
2194     listener = new Listener(name);
2195     this.port = listener.getAddress().getPort();
2196 
2197     this.metrics = new MetricsHBaseServer(name, new MetricsHBaseServerWrapperImpl(this));
2198     this.tcpNoDelay = conf.getBoolean("hbase.ipc.server.tcpnodelay", true);
2199     this.tcpKeepAlive = conf.getBoolean("hbase.ipc.server.tcpkeepalive", true);
2200 
2201     this.cellBlockBuilder = new CellBlockBuilder(conf);
2202 
2203     // Create the responder here
2204     responder = new Responder();
2205     this.authorize = conf.getBoolean(HADOOP_SECURITY_AUTHORIZATION, false);
2206     this.userProvider = UserProvider.instantiate(conf);
2207     this.isSecurityEnabled = userProvider.isHBaseSecurityEnabled();
2208     if (isSecurityEnabled) {
2209       HBaseSaslRpcServer.init(conf);
2210     }
2211     initReconfigurable(conf);
2212 
2213     this.scheduler = scheduler;
2214     this.scheduler.init(new RpcSchedulerContext(this));
2215   }
2216 
2217   @Override
2218   public void onConfigurationChange(Configuration newConf) {
2219     initReconfigurable(newConf);
2220     if (scheduler instanceof ConfigurationObserver) {
2221       ((ConfigurationObserver)scheduler).onConfigurationChange(newConf);
2222     }
2223   }
2224 
2225   private void initReconfigurable(Configuration confToLoad) {
2226     this.allowFallbackToSimpleAuth = confToLoad.getBoolean(FALLBACK_TO_INSECURE_CLIENT_AUTH, false);
2227     if (isSecurityEnabled && allowFallbackToSimpleAuth) {
2228       LOG.warn("********* WARNING! *********");
2229       LOG.warn("This server is configured to allow connections from INSECURE clients");
2230       LOG.warn("(" + FALLBACK_TO_INSECURE_CLIENT_AUTH + " = true).");
2231       LOG.warn("While this option is enabled, client identities cannot be secured, and user");
2232       LOG.warn("impersonation is possible!");
2233       LOG.warn("For secure operation, please disable SIMPLE authentication as soon as possible,");
2234       LOG.warn("by setting " + FALLBACK_TO_INSECURE_CLIENT_AUTH + " = false in hbase-site.xml");
2235       LOG.warn("****************************");
2236     }
2237   }
2238 
2239   /**
2240    * Subclasses of HBaseServer can override this to provide their own
2241    * Connection implementations.
2242    */
2243   protected Connection getConnection(SocketChannel channel, long time) {
2244     return new Connection(channel, time);
2245   }
2246 
2247   /**
2248    * Setup response for the RPC Call.
2249    *
2250    * @param response buffer to serialize the response into
2251    * @param call {@link Call} to which we are setting up the response
2252    * @param error error message, if the call failed
2253    * @throws IOException
2254    */
2255   private void setupResponse(ByteArrayOutputStream response, Call call, Throwable t, String error)
2256   throws IOException {
2257     if (response != null) response.reset();
2258     call.setResponse(null, null, t, error);
2259   }
2260 
2261   protected void closeConnection(Connection connection) {
2262     synchronized (connectionList) {
2263       if (connectionList.remove(connection)) {
2264         numConnections--;
2265       }
2266     }
2267     connection.close();
2268   }
2269 
2270   Configuration getConf() {
2271     return conf;
2272   }
2273 
2274   /** Sets the socket buffer size used for responding to RPCs.
2275    * @param size send size
2276    */
2277   @Override
2278   public void setSocketSendBufSize(int size) { this.socketSendBufferSize = size; }
2279 
2280   @Override
2281   public boolean isStarted() {
2282     return this.started;
2283   }
2284 
2285   /** Starts the service.  Must be called before any calls will be handled. */
2286   @Override
2287   public synchronized void start() {
2288     if (started) return;
2289     authTokenSecretMgr = createSecretManager();
2290     if (authTokenSecretMgr != null) {
2291       setSecretManager(authTokenSecretMgr);
2292       authTokenSecretMgr.start();
2293     }
2294     this.authManager = new ServiceAuthorizationManager();
2295     HBasePolicyProvider.init(conf, authManager);
2296     responder.start();
2297     listener.start();
2298     scheduler.start();
2299     started = true;
2300   }
2301 
2302   @Override
2303   public synchronized void refreshAuthManager(PolicyProvider pp) {
2304     // Ignore warnings that this should be accessed in a static way instead of via an instance;
2305     // it'll break if you go via static route.
2306     this.authManager.refresh(this.conf, pp);
2307   }
2308 
2309   private AuthenticationTokenSecretManager createSecretManager() {
2310     if (!isSecurityEnabled) return null;
2311     if (server == null) return null;
2312     Configuration conf = server.getConfiguration();
2313     long keyUpdateInterval =
2314         conf.getLong("hbase.auth.key.update.interval", 24*60*60*1000);
2315     long maxAge =
2316         conf.getLong("hbase.auth.token.max.lifetime", 7*24*60*60*1000);
2317     return new AuthenticationTokenSecretManager(conf, server.getZooKeeper(),
2318         server.getServerName().toString(), keyUpdateInterval, maxAge);
2319   }
2320 
2321   public SecretManager<? extends TokenIdentifier> getSecretManager() {
2322     return this.secretManager;
2323   }
2324 
2325   @SuppressWarnings("unchecked")
2326   public void setSecretManager(SecretManager<? extends TokenIdentifier> secretManager) {
2327     this.secretManager = (SecretManager<TokenIdentifier>) secretManager;
2328   }
2329 
2330   public Pair<Message, CellScanner> call(BlockingService service, MethodDescriptor md,
2331       Message param, CellScanner cellScanner, long receiveTime, MonitoredRPCHandler status)
2332       throws IOException {
2333     return call(service, md, param, cellScanner, receiveTime, status, System.currentTimeMillis(),0);
2334   }
2335 
2336   /**
2337    * This is a server side method, which is invoked over RPC. On success
2338    * the return response has protobuf response payload. On failure, the
2339    * exception name and the stack trace are returned in the protobuf response.
2340    */
2341   @Override
2342   public Pair<Message, CellScanner> call(BlockingService service, MethodDescriptor md,
2343       Message param, CellScanner cellScanner, long receiveTime, MonitoredRPCHandler status,
2344       long startTime, int timeout)
2345   throws IOException {
2346     try {
2347       status.setRPC(md.getName(), new Object[]{param}, receiveTime);
2348       // TODO: Review after we add in encoded data blocks.
2349       status.setRPCPacket(param);
2350       status.resume("Servicing call");
2351       //get an instance of the method arg type
2352       HBaseRpcController controller = new HBaseRpcControllerImpl(cellScanner);
2353       controller.setCallTimeout(timeout);
2354       Message result = service.callBlockingMethod(md, controller, param);
2355       long endTime = System.currentTimeMillis();
2356       int processingTime = (int) (endTime - startTime);
2357       int qTime = (int) (startTime - receiveTime);
2358       int totalTime = (int) (endTime - receiveTime);
2359       Call call = CurCall.get();
2360       if (LOG.isTraceEnabled()) {
2361         LOG.trace(CurCall.get().toString() +
2362             ", response " + TextFormat.shortDebugString(result) +
2363             " queueTime: " + qTime +
2364             " processingTime: " + processingTime +
2365             " totalTime: " + totalTime);
2366       }
2367       // Use the raw request call size for now.
2368       long requestSize = call.getSize();
2369       long responseSize = result.getSerializedSize();
2370       if (call.isClientCellBlockSupported()) {
2371         // Include the payload size in HBaseRpcController
2372         responseSize += call.getResponseCellSize();
2373       }
2374 
2375       metrics.dequeuedCall(qTime);
2376       metrics.processedCall(processingTime);
2377       metrics.totalCall(totalTime);
2378       metrics.receivedRequest(requestSize);
2379       metrics.sentResponse(responseSize);
2380       // log any RPC responses that are slower than the configured warn
2381       // response time or larger than configured warning size
2382       boolean tooSlow = (processingTime > warnResponseTime && warnResponseTime > -1);
2383       boolean tooLarge = (responseSize > warnResponseSize && warnResponseSize > -1);
2384       if (tooSlow || tooLarge) {
2385         // when tagging, we let TooLarge trump TooSmall to keep output simple
2386         // note that large responses will often also be slow.
2387         logResponse(param,
2388             md.getName(), md.getName() + "(" + param.getClass().getName() + ")",
2389             (tooLarge ? "TooLarge" : "TooSlow"),
2390             status.getClient(), startTime, processingTime, qTime,
2391             responseSize);
2392       }
2393       return new Pair<Message, CellScanner>(result, controller.cellScanner());
2394     } catch (Throwable e) {
2395       // The above callBlockingMethod will always return a SE.  Strip the SE wrapper before
2396       // putting it on the wire.  Its needed to adhere to the pb Service Interface but we don't
2397       // need to pass it over the wire.
2398       if (e instanceof ServiceException) {
2399         if (e.getCause() == null) {
2400           LOG.debug("Caught a ServiceException with null cause", e);
2401         } else {
2402           e = e.getCause();
2403         }
2404       }
2405 
2406       // increment the number of requests that were exceptions.
2407       metrics.exception(e);
2408 
2409       if (e instanceof LinkageError) throw new DoNotRetryIOException(e);
2410       if (e instanceof IOException) throw (IOException)e;
2411       LOG.error("Unexpected throwable object ", e);
2412       throw new IOException(e.getMessage(), e);
2413     }
2414   }
2415 
2416   /**
2417    * Logs an RPC response to the LOG file, producing valid JSON objects for
2418    * client Operations.
2419    * @param param The parameters received in the call.
2420    * @param methodName The name of the method invoked
2421    * @param call The string representation of the call
2422    * @param tag  The tag that will be used to indicate this event in the log.
2423    * @param clientAddress   The address of the client who made this call.
2424    * @param startTime       The time that the call was initiated, in ms.
2425    * @param processingTime  The duration that the call took to run, in ms.
2426    * @param qTime           The duration that the call spent on the queue
2427    *                        prior to being initiated, in ms.
2428    * @param responseSize    The size in bytes of the response buffer.
2429    */
2430   void logResponse(Message param, String methodName, String call, String tag,
2431       String clientAddress, long startTime, int processingTime, int qTime,
2432       long responseSize)
2433           throws IOException {
2434     // base information that is reported regardless of type of call
2435     Map<String, Object> responseInfo = new HashMap<String, Object>();
2436     responseInfo.put("starttimems", startTime);
2437     responseInfo.put("processingtimems", processingTime);
2438     responseInfo.put("queuetimems", qTime);
2439     responseInfo.put("responsesize", responseSize);
2440     responseInfo.put("client", clientAddress);
2441     responseInfo.put("class", server == null? "": server.getClass().getSimpleName());
2442     responseInfo.put("method", methodName);
2443     responseInfo.put("call", call);
2444     // The params could be really big, make sure they don't kill us at WARN
2445     String stringifiedParam = ProtobufUtil.getShortTextFormat(param);
2446     if (stringifiedParam.length() > 150) {
2447       // Truncate to 1000 chars if TRACE is on, else to 150 chars
2448       stringifiedParam = stringifiedParam.subSequence(
2449           0, LOG.isTraceEnabled() ? 1000 : 150) + " <TRUNCATED>";
2450     }
2451     responseInfo.put("param", stringifiedParam);
2452     if (param instanceof ClientProtos.ScanRequest && rsRpcServices != null) {
2453       ClientProtos.ScanRequest request = ((ClientProtos.ScanRequest) param);
2454       if (request.hasScannerId()) {
2455         long scannerId = request.getScannerId();
2456         String scanDetails = rsRpcServices.getScanDetailsWithId(scannerId);
2457         if (scanDetails != null) {
2458           responseInfo.put("scandetails", scanDetails);
2459         }
2460       }
2461     }
2462     LOG.warn("(response" + tag + "): " + MAPPER.writeValueAsString(responseInfo));
2463   }
2464 
2465   /** Stops the service.  No new calls will be handled after this is called. */
2466   @Override
2467   public synchronized void stop() {
2468     LOG.info("Stopping server on " + port);
2469     running = false;
2470     if (authTokenSecretMgr != null) {
2471       authTokenSecretMgr.stop();
2472       authTokenSecretMgr = null;
2473     }
2474     listener.interrupt();
2475     listener.doStop();
2476     responder.interrupt();
2477     scheduler.stop();
2478     notifyAll();
2479   }
2480 
2481   /** Wait for the server to be stopped.
2482    * Does not wait for all subthreads to finish.
2483    *  See {@link #stop()}.
2484    * @throws InterruptedException e
2485    */
2486   @Override
2487   public synchronized void join() throws InterruptedException {
2488     while (running) {
2489       wait();
2490     }
2491   }
2492 
2493   /**
2494    * Return the socket (ip+port) on which the RPC server is listening to. May return null if
2495    * the listener channel is closed.
2496    * @return the socket (ip+port) on which the RPC server is listening to, or null if this
2497    * information cannot be determined
2498    */
2499   @Override
2500   public synchronized InetSocketAddress getListenerAddress() {
2501     if (listener == null) {
2502       return null;
2503     }
2504     return listener.getAddress();
2505   }
2506 
2507   /**
2508    * Set the handler for calling out of RPC for error conditions.
2509    * @param handler the handler implementation
2510    */
2511   @Override
2512   public void setErrorHandler(HBaseRPCErrorHandler handler) {
2513     this.errorHandler = handler;
2514   }
2515 
2516   @Override
2517   public HBaseRPCErrorHandler getErrorHandler() {
2518     return this.errorHandler;
2519   }
2520 
2521   /**
2522    * Returns the metrics instance for reporting RPC call statistics
2523    */
2524   @Override
2525   public MetricsHBaseServer getMetrics() {
2526     return metrics;
2527   }
2528 
2529   @Override
2530   public void addCallSize(final long diff) {
2531     this.callQueueSize.add(diff);
2532   }
2533 
2534   /**
2535    * Authorize the incoming client connection.
2536    *
2537    * @param user client user
2538    * @param connection incoming connection
2539    * @param addr InetAddress of incoming connection
2540    * @throws org.apache.hadoop.security.authorize.AuthorizationException
2541    *         when the client isn't authorized to talk the protocol
2542    */
2543   public synchronized void authorize(UserGroupInformation user, ConnectionHeader connection,
2544       InetAddress addr)
2545   throws AuthorizationException {
2546     if (authorize) {
2547       Class<?> c = getServiceInterface(services, connection.getServiceName());
2548       this.authManager.authorize(user != null ? user : null, c, getConf(), addr);
2549     }
2550   }
2551 
2552   /**
2553    * When the read or write buffer size is larger than this limit, i/o will be
2554    * done in chunks of this size. Most RPC requests and responses would be
2555    * be smaller.
2556    */
2557   private static int NIO_BUFFER_LIMIT = 64 * 1024; //should not be more than 64KB.
2558 
2559   /**
2560    * This is a wrapper around {@link java.nio.channels.WritableByteChannel#write(java.nio.ByteBuffer)}.
2561    * If the amount of data is large, it writes to channel in smaller chunks.
2562    * This is to avoid jdk from creating many direct buffers as the size of
2563    * buffer increases. This also minimizes extra copies in NIO layer
2564    * as a result of multiple write operations required to write a large
2565    * buffer.
2566    *
2567    * @param channel writable byte channel to write to
2568    * @param bufferChain Chain of buffers to write
2569    * @return number of bytes written
2570    * @throws java.io.IOException e
2571    * @see java.nio.channels.WritableByteChannel#write(java.nio.ByteBuffer)
2572    */
2573   protected long channelWrite(GatheringByteChannel channel, BufferChain bufferChain)
2574   throws IOException {
2575     long count =  bufferChain.write(channel, NIO_BUFFER_LIMIT);
2576     if (count > 0) this.metrics.sentBytes(count);
2577     return count;
2578   }
2579 
2580   /**
2581    * This is a wrapper around {@link java.nio.channels.ReadableByteChannel#read(java.nio.ByteBuffer)}.
2582    * If the amount of data is large, it writes to channel in smaller chunks.
2583    * This is to avoid jdk from creating many direct buffers as the size of
2584    * ByteBuffer increases. There should not be any performance degredation.
2585    *
2586    * @param channel writable byte channel to write on
2587    * @param buffer buffer to write
2588    * @return number of bytes written
2589    * @throws java.io.IOException e
2590    * @see java.nio.channels.ReadableByteChannel#read(java.nio.ByteBuffer)
2591    */
2592   protected int channelRead(ReadableByteChannel channel,
2593                                    ByteBuffer buffer) throws IOException {
2594 
2595     int count = (buffer.remaining() <= NIO_BUFFER_LIMIT) ?
2596            channel.read(buffer) : channelIO(channel, null, buffer);
2597     if (count > 0) {
2598       metrics.receivedBytes(count);
2599     }
2600     return count;
2601   }
2602 
2603   /**
2604    * Helper for {@link #channelRead(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer)}
2605    * and {@link #channelWrite(GatheringByteChannel, BufferChain)}. Only
2606    * one of readCh or writeCh should be non-null.
2607    *
2608    * @param readCh read channel
2609    * @param writeCh write channel
2610    * @param buf buffer to read or write into/out of
2611    * @return bytes written
2612    * @throws java.io.IOException e
2613    * @see #channelRead(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer)
2614    * @see #channelWrite(GatheringByteChannel, BufferChain)
2615    */
2616   private static int channelIO(ReadableByteChannel readCh,
2617                                WritableByteChannel writeCh,
2618                                ByteBuffer buf) throws IOException {
2619 
2620     int originalLimit = buf.limit();
2621     int initialRemaining = buf.remaining();
2622     int ret = 0;
2623 
2624     while (buf.remaining() > 0) {
2625       try {
2626         int ioSize = Math.min(buf.remaining(), NIO_BUFFER_LIMIT);
2627         buf.limit(buf.position() + ioSize);
2628 
2629         ret = (readCh == null) ? writeCh.write(buf) : readCh.read(buf);
2630 
2631         if (ret < ioSize) {
2632           break;
2633         }
2634 
2635       } finally {
2636         buf.limit(originalLimit);
2637       }
2638     }
2639 
2640     int nBytes = initialRemaining - buf.remaining();
2641     return (nBytes > 0) ? nBytes : ret;
2642   }
2643 
2644   /**
2645    * Needed for features such as delayed calls.  We need to be able to store the current call
2646    * so that we can complete it later or ask questions of what is supported by the current ongoing
2647    * call.
2648    * @return An RpcCallContext backed by the currently ongoing call (gotten from a thread local)
2649    */
2650   public static RpcCallContext getCurrentCall() {
2651     return CurCall.get();
2652   }
2653 
2654   public static boolean isInRpcCallContext() {
2655     return CurCall.get() != null;
2656   }
2657 
2658   /**
2659    * Returns the user credentials associated with the current RPC request or
2660    * <code>null</code> if no credentials were provided.
2661    * @return A User
2662    */
2663   public static User getRequestUser() {
2664     RpcCallContext ctx = getCurrentCall();
2665     return ctx == null? null: ctx.getRequestUser();
2666   }
2667 
2668   /**
2669    * Returns the username for any user associated with the current RPC
2670    * request or <code>null</code> if no user is set.
2671    */
2672   public static String getRequestUserName() {
2673     User user = getRequestUser();
2674     return user == null? null: user.getShortName();
2675   }
2676 
2677   /**
2678    * @return Address of remote client if a request is ongoing, else null
2679    */
2680   public static InetAddress getRemoteAddress() {
2681     RpcCallContext ctx = getCurrentCall();
2682     return ctx == null? null: ctx.getRemoteAddress();
2683   }
2684 
2685   /**
2686    * @param serviceName Some arbitrary string that represents a 'service'.
2687    * @param services Available service instances
2688    * @return Matching BlockingServiceAndInterface pair
2689    */
2690   static BlockingServiceAndInterface getServiceAndInterface(
2691       final List<BlockingServiceAndInterface> services, final String serviceName) {
2692     for (BlockingServiceAndInterface bs : services) {
2693       if (bs.getBlockingService().getDescriptorForType().getName().equals(serviceName)) {
2694         return bs;
2695       }
2696     }
2697     return null;
2698   }
2699 
2700   /**
2701    * @param serviceName Some arbitrary string that represents a 'service'.
2702    * @param services Available services and their service interfaces.
2703    * @return Service interface class for <code>serviceName</code>
2704    */
2705   static Class<?> getServiceInterface(
2706       final List<BlockingServiceAndInterface> services,
2707       final String serviceName) {
2708     BlockingServiceAndInterface bsasi =
2709         getServiceAndInterface(services, serviceName);
2710     return bsasi == null? null: bsasi.getServiceInterface();
2711   }
2712 
2713   /**
2714    * @param serviceName Some arbitrary string that represents a 'service'.
2715    * @param services Available services and their service interfaces.
2716    * @return BlockingService that goes with the passed <code>serviceName</code>
2717    */
2718   static BlockingService getService(
2719       final List<BlockingServiceAndInterface> services,
2720       final String serviceName) {
2721     BlockingServiceAndInterface bsasi =
2722         getServiceAndInterface(services, serviceName);
2723     return bsasi == null? null: bsasi.getBlockingService();
2724   }
2725 
2726   static MonitoredRPCHandler getStatus() {
2727     // It is ugly the way we park status up in RpcServer.  Let it be for now.  TODO.
2728     MonitoredRPCHandler status = RpcServer.MONITORED_RPC.get();
2729     if (status != null) {
2730       return status;
2731     }
2732     status = TaskMonitor.get().createRPCStatus(Thread.currentThread().getName());
2733     status.pause("Waiting for a call");
2734     RpcServer.MONITORED_RPC.set(status);
2735     return status;
2736   }
2737 
2738   /** Returns the remote side ip address when invoked inside an RPC
2739    *  Returns null incase of an error.
2740    *  @return InetAddress
2741    */
2742   public static InetAddress getRemoteIp() {
2743     Call call = CurCall.get();
2744     if (call != null && call.connection != null && call.connection.socket != null) {
2745       return call.connection.socket.getInetAddress();
2746     }
2747     return null;
2748   }
2749 
2750 
2751   /**
2752    * A convenience method to bind to a given address and report
2753    * better exceptions if the address is not a valid host.
2754    * @param socket the socket to bind
2755    * @param address the address to bind to
2756    * @param backlog the number of connections allowed in the queue
2757    * @throws BindException if the address can't be bound
2758    * @throws UnknownHostException if the address isn't a valid host name
2759    * @throws IOException other random errors from bind
2760    */
2761   public static void bind(ServerSocket socket, InetSocketAddress address,
2762                           int backlog) throws IOException {
2763     try {
2764       socket.bind(address, backlog);
2765     } catch (BindException e) {
2766       BindException bindException =
2767         new BindException("Problem binding to " + address + " : " +
2768             e.getMessage());
2769       bindException.initCause(e);
2770       throw bindException;
2771     } catch (SocketException e) {
2772       // If they try to bind to a different host's address, give a better
2773       // error message.
2774       if ("Unresolved address".equals(e.getMessage())) {
2775         throw new UnknownHostException("Invalid hostname for server: " +
2776                                        address.getHostName());
2777       }
2778       throw e;
2779     }
2780   }
2781 
2782   @Override
2783   public RpcScheduler getScheduler() {
2784     return scheduler;
2785   }
2786 
2787   @Override
2788   public void setRsRpcServices(RSRpcServices rsRpcServices) {
2789     this.rsRpcServices = rsRpcServices;
2790   }
2791 }