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