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