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