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