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