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