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