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