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