1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.ipc;
21
22 import com.google.protobuf.Descriptors.MethodDescriptor;
23 import com.google.protobuf.Message;
24 import com.google.protobuf.Message.Builder;
25 import com.google.protobuf.RpcCallback;
26 import org.apache.hadoop.conf.Configuration;
27 import org.apache.hadoop.hbase.CellScanner;
28 import org.apache.hadoop.hbase.DoNotRetryIOException;
29 import org.apache.hadoop.hbase.HConstants;
30 import org.apache.hadoop.hbase.ServerName;
31 import org.apache.hadoop.hbase.classification.InterfaceAudience;
32 import org.apache.hadoop.hbase.codec.Codec;
33 import org.apache.hadoop.hbase.exceptions.ConnectionClosingException;
34 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
35 import org.apache.hadoop.hbase.protobuf.generated.AuthenticationProtos;
36 import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.CellBlockMeta;
37 import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.ConnectionHeader;
38 import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.ExceptionResponse;
39 import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.RequestHeader;
40 import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.ResponseHeader;
41 import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.UserInformation;
42 import org.apache.hadoop.hbase.protobuf.generated.TracingProtos.RPCTInfo;
43 import org.apache.hadoop.hbase.security.AuthMethod;
44 import org.apache.hadoop.hbase.security.HBaseSaslRpcClient;
45 import org.apache.hadoop.hbase.security.SaslUtil.QualityOfProtection;
46 import org.apache.hadoop.hbase.security.SecurityInfo;
47 import org.apache.hadoop.hbase.security.User;
48 import org.apache.hadoop.hbase.security.UserProvider;
49 import org.apache.hadoop.hbase.security.token.AuthenticationTokenSelector;
50 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
51 import org.apache.hadoop.hbase.util.ExceptionUtil;
52 import org.apache.hadoop.hbase.util.Pair;
53 import org.apache.hadoop.hbase.util.PoolMap;
54 import org.apache.hadoop.io.IOUtils;
55 import org.apache.hadoop.io.Text;
56 import org.apache.hadoop.io.compress.CompressionCodec;
57 import org.apache.hadoop.ipc.RemoteException;
58 import org.apache.hadoop.net.NetUtils;
59 import org.apache.hadoop.security.SecurityUtil;
60 import org.apache.hadoop.security.UserGroupInformation;
61 import org.apache.hadoop.security.token.Token;
62 import org.apache.hadoop.security.token.TokenIdentifier;
63 import org.apache.hadoop.security.token.TokenSelector;
64 import org.apache.htrace.Span;
65 import org.apache.htrace.Trace;
66 import org.apache.htrace.TraceScope;
67
68 import javax.net.SocketFactory;
69 import javax.security.sasl.SaslException;
70 import java.io.BufferedInputStream;
71 import java.io.BufferedOutputStream;
72 import java.io.Closeable;
73 import java.io.DataInputStream;
74 import java.io.DataOutputStream;
75 import java.io.IOException;
76 import java.io.InputStream;
77 import java.io.InterruptedIOException;
78 import java.io.OutputStream;
79 import java.net.ConnectException;
80 import java.net.InetSocketAddress;
81 import java.net.Socket;
82 import java.net.SocketAddress;
83 import java.net.SocketTimeoutException;
84 import java.net.UnknownHostException;
85 import java.nio.ByteBuffer;
86 import java.security.PrivilegedExceptionAction;
87 import java.util.HashMap;
88 import java.util.Iterator;
89 import java.util.Map;
90 import java.util.Map.Entry;
91 import java.util.Random;
92 import java.util.concurrent.ArrayBlockingQueue;
93 import java.util.concurrent.BlockingQueue;
94 import java.util.concurrent.ConcurrentSkipListMap;
95 import java.util.concurrent.atomic.AtomicBoolean;
96 import java.util.concurrent.atomic.AtomicInteger;
97
98
99
100
101
102 @InterfaceAudience.Private
103 public class RpcClientImpl extends AbstractRpcClient {
104 protected final AtomicInteger callIdCnt = new AtomicInteger();
105
106 protected final PoolMap<ConnectionId, Connection> connections;
107
108 protected final AtomicBoolean running = new AtomicBoolean(true);
109
110 protected final FailedServers failedServers;
111
112 protected final SocketFactory socketFactory;
113
114 protected final static Map<AuthenticationProtos.TokenIdentifier.Kind,
115 TokenSelector<? extends TokenIdentifier>> tokenHandlers =
116 new HashMap<AuthenticationProtos.TokenIdentifier.Kind,
117 TokenSelector<? extends TokenIdentifier>>();
118 static {
119 tokenHandlers.put(AuthenticationProtos.TokenIdentifier.Kind.HBASE_AUTH_TOKEN,
120 new AuthenticationTokenSelector());
121 }
122
123
124
125
126
127 protected Connection createConnection(ConnectionId remoteId, final Codec codec,
128 final CompressionCodec compressor)
129 throws IOException {
130 return new Connection(remoteId, codec, compressor);
131 }
132
133
134
135
136 private static class CallFuture {
137 final Call call;
138 final int priority;
139 final Span span;
140
141
142 final static CallFuture DEATH_PILL = new CallFuture(null, -1, null);
143
144 CallFuture(Call call, int priority, Span span) {
145 this.call = call;
146 this.priority = priority;
147 this.span = span;
148 }
149 }
150
151
152
153
154 protected class Connection extends Thread {
155 private ConnectionHeader header;
156 protected ConnectionId remoteId;
157 protected Socket socket = null;
158 protected DataInputStream in;
159 protected DataOutputStream out;
160 private Object outLock = new Object();
161 private InetSocketAddress server;
162 private String serverPrincipal;
163 private AuthMethod authMethod;
164 private boolean useSasl;
165 private Token<? extends TokenIdentifier> token;
166 private HBaseSaslRpcClient saslRpcClient;
167 private int reloginMaxBackoff;
168 private final Codec codec;
169 private final CompressionCodec compressor;
170
171
172 protected final ConcurrentSkipListMap<Integer, Call> calls =
173 new ConcurrentSkipListMap<Integer, Call>();
174
175 protected final AtomicBoolean shouldCloseConnection = new AtomicBoolean();
176 protected final CallSender callSender;
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197 private class CallSender extends Thread implements Closeable {
198 protected final BlockingQueue<CallFuture> callsToWrite;
199
200
201 public CallFuture sendCall(Call call, int priority, Span span)
202 throws InterruptedException, IOException {
203 CallFuture cts = new CallFuture(call, priority, span);
204 if (!callsToWrite.offer(cts)) {
205 throw new IOException("Can't add the call " + call.id +
206 " to the write queue. callsToWrite.size()=" + callsToWrite.size());
207 }
208 checkIsOpen();
209
210 return cts;
211 }
212
213 @Override
214 public void close(){
215 assert shouldCloseConnection.get();
216 callsToWrite.offer(CallFuture.DEATH_PILL);
217
218
219 }
220
221 CallSender(String name, Configuration conf) {
222 int queueSize = conf.getInt("hbase.ipc.client.write.queueSize", 1000);
223 callsToWrite = new ArrayBlockingQueue<CallFuture>(queueSize);
224 setDaemon(true);
225 setName(name + " - writer");
226 }
227
228 public void remove(CallFuture cts){
229 callsToWrite.remove(cts);
230
231
232
233 calls.remove(cts.call.id);
234 cts.call.callComplete();
235 }
236
237
238
239
240 @Override
241 public void run() {
242 while (!shouldCloseConnection.get()) {
243 CallFuture cts = null;
244 try {
245 cts = callsToWrite.take();
246 } catch (InterruptedException e) {
247 markClosed(new InterruptedIOException());
248 }
249
250 if (cts == null || cts == CallFuture.DEATH_PILL) {
251 assert shouldCloseConnection.get();
252 break;
253 }
254
255 if (cts.call.done) {
256 continue;
257 }
258
259 if (cts.call.checkAndSetTimeout()) {
260 continue;
261 }
262
263 try {
264 Connection.this.tracedWriteRequest(cts.call, cts.priority, cts.span);
265 } catch (IOException e) {
266 if (LOG.isDebugEnabled()) {
267 LOG.debug("call write error for call #" + cts.call.id
268 + ", message =" + e.getMessage());
269 }
270 cts.call.setException(e);
271 markClosed(e);
272 }
273 }
274
275 cleanup();
276 }
277
278
279
280
281 private void cleanup() {
282 assert shouldCloseConnection.get();
283
284 IOException ie = new ConnectionClosingException("Connection to " + server + " is closing.");
285 while (true) {
286 CallFuture cts = callsToWrite.poll();
287 if (cts == null) {
288 break;
289 }
290 if (cts.call != null && !cts.call.done) {
291 cts.call.setException(ie);
292 }
293 }
294 }
295 }
296
297 Connection(ConnectionId remoteId, final Codec codec, final CompressionCodec compressor)
298 throws IOException {
299 if (remoteId.getAddress().isUnresolved()) {
300 throw new UnknownHostException("unknown host: " + remoteId.getAddress().getHostName());
301 }
302 this.server = remoteId.getAddress();
303 this.codec = codec;
304 this.compressor = compressor;
305
306 UserGroupInformation ticket = remoteId.getTicket().getUGI();
307 SecurityInfo securityInfo = SecurityInfo.getInfo(remoteId.getServiceName());
308 this.useSasl = userProvider.isHBaseSecurityEnabled();
309 if (useSasl && securityInfo != null) {
310 AuthenticationProtos.TokenIdentifier.Kind tokenKind = securityInfo.getTokenKind();
311 if (tokenKind != null) {
312 TokenSelector<? extends TokenIdentifier> tokenSelector =
313 tokenHandlers.get(tokenKind);
314 if (tokenSelector != null) {
315 token = tokenSelector.selectToken(new Text(clusterId),
316 ticket.getTokens());
317 } else if (LOG.isDebugEnabled()) {
318 LOG.debug("No token selector found for type "+tokenKind);
319 }
320 }
321 String serverKey = securityInfo.getServerPrincipal();
322 if (serverKey == null) {
323 throw new IOException(
324 "Can't obtain server Kerberos config key from SecurityInfo");
325 }
326 serverPrincipal = SecurityUtil.getServerPrincipal(
327 conf.get(serverKey), server.getAddress().getCanonicalHostName().toLowerCase());
328 if (LOG.isDebugEnabled()) {
329 LOG.debug("RPC Server Kerberos principal name for service="
330 + remoteId.getServiceName() + " is " + serverPrincipal);
331 }
332 }
333
334 if (!useSasl) {
335 authMethod = AuthMethod.SIMPLE;
336 } else if (token != null) {
337 authMethod = AuthMethod.DIGEST;
338 } else {
339 authMethod = AuthMethod.KERBEROS;
340 }
341
342 if (LOG.isDebugEnabled()) {
343 LOG.debug("Use " + authMethod + " authentication for service " + remoteId.serviceName +
344 ", sasl=" + useSasl);
345 }
346 reloginMaxBackoff = conf.getInt("hbase.security.relogin.maxbackoff", 5000);
347 this.remoteId = remoteId;
348
349 ConnectionHeader.Builder builder = ConnectionHeader.newBuilder();
350 builder.setServiceName(remoteId.getServiceName());
351 UserInformation userInfoPB = getUserInfo(ticket);
352 if (userInfoPB != null) {
353 builder.setUserInfo(userInfoPB);
354 }
355 if (this.codec != null) {
356 builder.setCellBlockCodecClass(this.codec.getClass().getCanonicalName());
357 }
358 if (this.compressor != null) {
359 builder.setCellBlockCompressorClass(this.compressor.getClass().getCanonicalName());
360 }
361 builder.setVersionInfo(ProtobufUtil.getVersionInfo());
362 this.header = builder.build();
363
364 this.setName("IPC Client (" + socketFactory.hashCode() +") connection to " +
365 remoteId.getAddress().toString() +
366 ((ticket==null)?" from an unknown user": (" from "
367 + ticket.getUserName())));
368 this.setDaemon(true);
369
370 if (conf.getBoolean(SPECIFIC_WRITE_THREAD, false)) {
371 callSender = new CallSender(getName(), conf);
372 callSender.start();
373 } else {
374 callSender = null;
375 }
376 }
377
378 private UserInformation getUserInfo(UserGroupInformation ugi) {
379 if (ugi == null || authMethod == AuthMethod.DIGEST) {
380
381 return null;
382 }
383 UserInformation.Builder userInfoPB = UserInformation.newBuilder();
384 if (authMethod == AuthMethod.KERBEROS) {
385
386 userInfoPB.setEffectiveUser(ugi.getUserName());
387 } else if (authMethod == AuthMethod.SIMPLE) {
388
389 userInfoPB.setEffectiveUser(ugi.getUserName());
390 if (ugi.getRealUser() != null) {
391 userInfoPB.setRealUser(ugi.getRealUser().getUserName());
392 }
393 }
394 return userInfoPB.build();
395 }
396
397 protected synchronized void setupConnection() throws IOException {
398 short ioFailures = 0;
399 short timeoutFailures = 0;
400 while (true) {
401 try {
402 this.socket = socketFactory.createSocket();
403 this.socket.setTcpNoDelay(tcpNoDelay);
404 this.socket.setKeepAlive(tcpKeepAlive);
405 if (localAddr != null) {
406 this.socket.bind(localAddr);
407 }
408 NetUtils.connect(this.socket, remoteId.getAddress(), connectTO);
409 this.socket.setSoTimeout(readTO);
410 return;
411 } catch (SocketTimeoutException toe) {
412
413
414
415 handleConnectionFailure(timeoutFailures++, maxRetries, toe);
416 } catch (IOException ie) {
417 handleConnectionFailure(ioFailures++, maxRetries, ie);
418 }
419 }
420 }
421
422 protected synchronized void closeConnection() {
423 if (socket == null) {
424 return;
425 }
426
427
428 try {
429 if (socket.getOutputStream() != null) {
430 socket.getOutputStream().close();
431 }
432 } catch (IOException ignored) {
433 if (LOG.isTraceEnabled()) LOG.trace("ignored", ignored);
434 }
435 try {
436 if (socket.getInputStream() != null) {
437 socket.getInputStream().close();
438 }
439 } catch (IOException ignored) {
440 if (LOG.isTraceEnabled()) LOG.trace("ignored", ignored);
441 }
442 try {
443 if (socket.getChannel() != null) {
444 socket.getChannel().close();
445 }
446 } catch (IOException ignored) {
447 if (LOG.isTraceEnabled()) LOG.trace("ignored", ignored);
448 }
449 try {
450 socket.close();
451 } catch (IOException e) {
452 LOG.warn("Not able to close a socket", e);
453 }
454
455
456
457 socket = null;
458 }
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475 private void handleConnectionFailure(int curRetries, int maxRetries, IOException ioe)
476 throws IOException {
477 closeConnection();
478
479
480 if (curRetries >= maxRetries || ExceptionUtil.isInterrupt(ioe)) {
481 throw ioe;
482 }
483
484
485 try {
486 Thread.sleep(failureSleep);
487 } catch (InterruptedException ie) {
488 ExceptionUtil.rethrowIfInterrupt(ie);
489 }
490
491 LOG.info("Retrying connect to server: " + remoteId.getAddress() +
492 " after sleeping " + failureSleep + "ms. Already tried " + curRetries +
493 " time(s).");
494 }
495
496
497
498
499 private void checkIsOpen() throws IOException {
500 if (shouldCloseConnection.get()) {
501 throw new ConnectionClosingException(getName() + " is closing");
502 }
503 }
504
505
506
507
508
509
510
511 protected synchronized boolean waitForWork() throws InterruptedException {
512
513
514 long waitUntil = EnvironmentEdgeManager.currentTime() + minIdleTimeBeforeClose;
515
516 while (true) {
517 if (shouldCloseConnection.get()) {
518 return false;
519 }
520
521 if (!running.get()) {
522 markClosed(new IOException("stopped with " + calls.size() + " pending request(s)"));
523 return false;
524 }
525
526 if (!calls.isEmpty()) {
527
528
529 return true;
530 }
531
532 if (EnvironmentEdgeManager.currentTime() >= waitUntil) {
533
534
535
536
537 markClosed(new IOException(
538 "idle connection closed with " + calls.size() + " pending request(s)"));
539 return false;
540 }
541
542 wait(Math.min(minIdleTimeBeforeClose, 1000));
543 }
544 }
545
546 public InetSocketAddress getRemoteAddress() {
547 return remoteId.getAddress();
548 }
549
550 @Override
551 public void run() {
552 if (LOG.isTraceEnabled()) {
553 LOG.trace(getName() + ": starting, connections " + connections.size());
554 }
555
556 try {
557 while (waitForWork()) {
558 readResponse();
559 }
560 } catch (InterruptedException t) {
561 if (LOG.isTraceEnabled()) {
562 LOG.trace(getName() + ": interrupted while waiting for call responses");
563 }
564 markClosed(ExceptionUtil.asInterrupt(t));
565 } catch (Throwable t) {
566 if (LOG.isDebugEnabled()) {
567 LOG.debug(getName() + ": unexpected throwable while waiting for call responses", t);
568 }
569 markClosed(new IOException("Unexpected throwable while waiting call responses", t));
570 }
571
572 close();
573
574 if (LOG.isTraceEnabled()) {
575 LOG.trace(getName() + ": stopped, connections " + connections.size());
576 }
577 }
578
579 private synchronized void disposeSasl() {
580 if (saslRpcClient != null) {
581 try {
582 saslRpcClient.dispose();
583 saslRpcClient = null;
584 } catch (IOException ioe) {
585 LOG.error("Error disposing of SASL client", ioe);
586 }
587 }
588 }
589
590 private synchronized boolean shouldAuthenticateOverKrb() throws IOException {
591 UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
592 UserGroupInformation currentUser =
593 UserGroupInformation.getCurrentUser();
594 UserGroupInformation realUser = currentUser.getRealUser();
595 return authMethod == AuthMethod.KERBEROS &&
596 loginUser != null &&
597
598 loginUser.hasKerberosCredentials() &&
599
600
601 (loginUser.equals(currentUser) || loginUser.equals(realUser));
602 }
603
604 private synchronized boolean setupSaslConnection(final InputStream in2,
605 final OutputStream out2) throws IOException {
606 saslRpcClient = new HBaseSaslRpcClient(authMethod, token, serverPrincipal, fallbackAllowed,
607 conf.get("hbase.rpc.protection",
608 QualityOfProtection.AUTHENTICATION.name().toLowerCase()));
609 return saslRpcClient.saslConnect(in2, out2);
610 }
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630 private synchronized void handleSaslConnectionFailure(
631 final int currRetries,
632 final int maxRetries, final Exception ex, final Random rand,
633 final UserGroupInformation user)
634 throws IOException, InterruptedException{
635 user.doAs(new PrivilegedExceptionAction<Object>() {
636 @Override
637 public Object run() throws IOException, InterruptedException {
638 closeConnection();
639 if (shouldAuthenticateOverKrb()) {
640 if (currRetries < maxRetries) {
641 if (LOG.isDebugEnabled()) {
642 LOG.debug("Exception encountered while connecting to " +
643 "the server : " + ex);
644 }
645
646 if (UserGroupInformation.isLoginKeytabBased()) {
647 UserGroupInformation.getLoginUser().reloginFromKeytab();
648 } else {
649 UserGroupInformation.getLoginUser().reloginFromTicketCache();
650 }
651 disposeSasl();
652
653
654
655
656 Thread.sleep((rand.nextInt(reloginMaxBackoff) + 1));
657 return null;
658 } else {
659 String msg = "Couldn't setup connection for " +
660 UserGroupInformation.getLoginUser().getUserName() +
661 " to " + serverPrincipal;
662 LOG.warn(msg);
663 throw (IOException) new IOException(msg).initCause(ex);
664 }
665 } else {
666 LOG.warn("Exception encountered while connecting to " +
667 "the server : " + ex);
668 }
669 if (ex instanceof RemoteException) {
670 throw (RemoteException)ex;
671 }
672 if (ex instanceof SaslException) {
673 String msg = "SASL authentication failed." +
674 " The most likely cause is missing or invalid credentials." +
675 " Consider 'kinit'.";
676 LOG.fatal(msg, ex);
677 throw new RuntimeException(msg, ex);
678 }
679 throw new IOException(ex);
680 }
681 });
682 }
683
684 protected synchronized void setupIOstreams() throws IOException {
685 if (socket != null) {
686
687 return;
688 }
689
690 if (shouldCloseConnection.get()){
691 throw new ConnectionClosingException("This connection is closing");
692 }
693
694 if (failedServers.isFailedServer(remoteId.getAddress())) {
695 if (LOG.isDebugEnabled()) {
696 LOG.debug("Not trying to connect to " + server +
697 " this server is in the failed servers list");
698 }
699 IOException e = new FailedServerException(
700 "This server is in the failed servers list: " + server);
701 markClosed(e);
702 close();
703 throw e;
704 }
705
706 try {
707 if (LOG.isDebugEnabled()) {
708 LOG.debug("Connecting to " + server);
709 }
710 short numRetries = 0;
711 final short MAX_RETRIES = 5;
712 Random rand = null;
713 while (true) {
714 setupConnection();
715 InputStream inStream = NetUtils.getInputStream(socket);
716
717 OutputStream outStream = NetUtils.getOutputStream(socket, writeTO);
718
719 writeConnectionHeaderPreamble(outStream);
720 if (useSasl) {
721 final InputStream in2 = inStream;
722 final OutputStream out2 = outStream;
723 UserGroupInformation ticket = remoteId.getTicket().getUGI();
724 if (authMethod == AuthMethod.KERBEROS) {
725 if (ticket != null && ticket.getRealUser() != null) {
726 ticket = ticket.getRealUser();
727 }
728 }
729 boolean continueSasl;
730 if (ticket == null) throw new FatalConnectionException("ticket/user is null");
731 try {
732 continueSasl = ticket.doAs(new PrivilegedExceptionAction<Boolean>() {
733 @Override
734 public Boolean run() throws IOException {
735 return setupSaslConnection(in2, out2);
736 }
737 });
738 } catch (Exception ex) {
739 ExceptionUtil.rethrowIfInterrupt(ex);
740 if (rand == null) {
741 rand = new Random();
742 }
743 handleSaslConnectionFailure(numRetries++, MAX_RETRIES, ex, rand, ticket);
744 continue;
745 }
746 if (continueSasl) {
747
748 inStream = saslRpcClient.getInputStream(inStream);
749 outStream = saslRpcClient.getOutputStream(outStream);
750 } else {
751
752 authMethod = AuthMethod.SIMPLE;
753 useSasl = false;
754 }
755 }
756 this.in = new DataInputStream(new BufferedInputStream(inStream));
757 synchronized (this.outLock) {
758 this.out = new DataOutputStream(new BufferedOutputStream(outStream));
759 }
760
761 writeConnectionHeader();
762
763
764 start();
765 return;
766 }
767 } catch (Throwable t) {
768 IOException e = ExceptionUtil.asInterrupt(t);
769 if (e == null) {
770 failedServers.addToFailedServers(remoteId.address);
771 if (t instanceof LinkageError) {
772
773 e = new DoNotRetryIOException(t);
774 } else if (t instanceof IOException) {
775 e = (IOException) t;
776 } else {
777 e = new IOException("Could not set up IO Streams to " + server, t);
778 }
779 }
780 markClosed(e);
781 close();
782 throw e;
783 }
784 }
785
786
787
788
789 private void writeConnectionHeaderPreamble(OutputStream outStream) throws IOException {
790
791
792
793
794
795 int rpcHeaderLen = HConstants.RPC_HEADER.length;
796 byte [] preamble = new byte [rpcHeaderLen + 2];
797 System.arraycopy(HConstants.RPC_HEADER, 0, preamble, 0, rpcHeaderLen);
798 preamble[rpcHeaderLen] = HConstants.RPC_CURRENT_VERSION;
799 preamble[rpcHeaderLen + 1] = authMethod.code;
800 outStream.write(preamble);
801 outStream.flush();
802 }
803
804
805
806
807 private synchronized void writeConnectionHeader() throws IOException {
808 synchronized (this.outLock) {
809 this.out.writeInt(this.header.getSerializedSize());
810 this.header.writeTo(this.out);
811 this.out.flush();
812 }
813 }
814
815
816 protected synchronized void close() {
817 if (!shouldCloseConnection.get()) {
818 LOG.error(getName() + ": the connection is not in the closed state");
819 return;
820 }
821
822
823
824 synchronized (connections) {
825 connections.removeValue(remoteId, this);
826 }
827
828
829 synchronized(this.outLock) {
830 if (this.out != null) {
831 IOUtils.closeStream(out);
832 this.out = null;
833 }
834 }
835 IOUtils.closeStream(in);
836 this.in = null;
837 disposeSasl();
838
839
840 if (LOG.isTraceEnabled()) {
841 LOG.trace(getName() + ": closing ipc connection to " + server);
842 }
843
844 cleanupCalls(true);
845
846 if (LOG.isTraceEnabled()) {
847 LOG.trace(getName() + ": ipc connection to " + server + " closed");
848 }
849 }
850
851 protected void tracedWriteRequest(Call call, int priority, Span span) throws IOException {
852 TraceScope ts = Trace.continueSpan(span);
853 try {
854 writeRequest(call, priority, span);
855 } finally {
856 ts.close();
857 }
858 }
859
860
861
862
863
864
865
866 private void writeRequest(Call call, final int priority, Span span) throws IOException {
867 RequestHeader.Builder builder = RequestHeader.newBuilder();
868 builder.setCallId(call.id);
869 if (span != null) {
870 builder.setTraceInfo(
871 RPCTInfo.newBuilder().setParentId(span.getSpanId()).setTraceId(span.getTraceId()));
872 }
873 builder.setMethodName(call.md.getName());
874 builder.setRequestParam(call.param != null);
875 ByteBuffer cellBlock = ipcUtil.buildCellBlock(this.codec, this.compressor, call.cells);
876 if (cellBlock != null) {
877 CellBlockMeta.Builder cellBlockBuilder = CellBlockMeta.newBuilder();
878 cellBlockBuilder.setLength(cellBlock.limit());
879 builder.setCellBlockMeta(cellBlockBuilder.build());
880 }
881
882 if (priority != 0) builder.setPriority(priority);
883 RequestHeader header = builder.build();
884
885 setupIOstreams();
886
887
888
889
890 checkIsOpen();
891 IOException writeException = null;
892 synchronized (this.outLock) {
893 if (Thread.interrupted()) throw new InterruptedIOException();
894
895 calls.put(call.id, call);
896 checkIsOpen();
897
898 try {
899 IPCUtil.write(this.out, header, call.param, cellBlock);
900 } catch (IOException e) {
901
902
903 shouldCloseConnection.set(true);
904 writeException = e;
905 interrupt();
906 }
907 }
908
909
910
911 synchronized (this) {
912 notifyAll();
913 }
914
915
916 if (writeException != null) throw writeException;
917 }
918
919
920
921
922 protected void readResponse() {
923 if (shouldCloseConnection.get()) return;
924 Call call = null;
925 boolean expectedCall = false;
926 try {
927
928
929 int totalSize = in.readInt();
930
931
932 ResponseHeader responseHeader = ResponseHeader.parseDelimitedFrom(in);
933 int id = responseHeader.getCallId();
934 call = calls.remove(id);
935 expectedCall = (call != null && !call.done);
936 if (!expectedCall) {
937
938
939
940
941
942 int readSoFar = IPCUtil.getTotalSizeWhenWrittenDelimited(responseHeader);
943 int whatIsLeftToRead = totalSize - readSoFar;
944 IOUtils.skipFully(in, whatIsLeftToRead);
945 return;
946 }
947 if (responseHeader.hasException()) {
948 ExceptionResponse exceptionResponse = responseHeader.getException();
949 RemoteException re = createRemoteException(exceptionResponse);
950 call.setException(re);
951 if (isFatalConnectionException(exceptionResponse)) {
952 markClosed(re);
953 }
954 } else {
955 Message value = null;
956 if (call.responseDefaultType != null) {
957 Builder builder = call.responseDefaultType.newBuilderForType();
958 builder.mergeDelimitedFrom(in);
959 value = builder.build();
960 }
961 CellScanner cellBlockScanner = null;
962 if (responseHeader.hasCellBlockMeta()) {
963 int size = responseHeader.getCellBlockMeta().getLength();
964 byte [] cellBlock = new byte[size];
965 IOUtils.readFully(this.in, cellBlock, 0, cellBlock.length);
966 cellBlockScanner = ipcUtil.createCellScanner(this.codec, this.compressor, cellBlock);
967 }
968 call.setResponse(value, cellBlockScanner);
969 }
970 } catch (IOException e) {
971 if (expectedCall) call.setException(e);
972 if (e instanceof SocketTimeoutException) {
973
974
975
976 if (LOG.isTraceEnabled()) LOG.trace("ignored", e);
977 } else {
978
979 markClosed(e);
980 }
981 } finally {
982 cleanupCalls(false);
983 }
984 }
985
986
987
988
989 private boolean isFatalConnectionException(final ExceptionResponse e) {
990 return e.getExceptionClassName().
991 equals(FatalConnectionException.class.getName());
992 }
993
994
995
996
997
998 private RemoteException createRemoteException(final ExceptionResponse e) {
999 String innerExceptionClassName = e.getExceptionClassName();
1000 boolean doNotRetry = e.getDoNotRetry();
1001 return e.hasHostname()?
1002
1003 new RemoteWithExtrasException(innerExceptionClassName,
1004 e.getStackTrace(), e.getHostname(), e.getPort(), doNotRetry):
1005 new RemoteWithExtrasException(innerExceptionClassName,
1006 e.getStackTrace(), doNotRetry);
1007 }
1008
1009 protected synchronized void markClosed(IOException e) {
1010 if (e == null) throw new NullPointerException();
1011
1012 if (shouldCloseConnection.compareAndSet(false, true)) {
1013 if (LOG.isTraceEnabled()) {
1014 LOG.trace(getName() + ": marking at should close, reason: " + e.getMessage());
1015 }
1016 if (callSender != null) {
1017 callSender.close();
1018 }
1019 notifyAll();
1020 }
1021 }
1022
1023
1024
1025
1026
1027
1028 protected synchronized void cleanupCalls(boolean allCalls) {
1029 Iterator<Entry<Integer, Call>> itor = calls.entrySet().iterator();
1030 while (itor.hasNext()) {
1031 Call c = itor.next().getValue();
1032 if (c.done) {
1033
1034 itor.remove();
1035 } else if (allCalls) {
1036 long waitTime = EnvironmentEdgeManager.currentTime() - c.getStartTime();
1037 IOException ie = new ConnectionClosingException("Connection to " + getRemoteAddress()
1038 + " is closing. Call id=" + c.id + ", waitTime=" + waitTime);
1039 c.setException(ie);
1040 itor.remove();
1041 } else if (c.checkAndSetTimeout()) {
1042 itor.remove();
1043 } else {
1044
1045
1046
1047 break;
1048 }
1049 }
1050 }
1051 }
1052
1053
1054
1055
1056
1057
1058
1059 RpcClientImpl(Configuration conf, String clusterId, SocketFactory factory) {
1060 this(conf, clusterId, factory, null);
1061 }
1062
1063
1064
1065
1066
1067
1068
1069
1070 RpcClientImpl(Configuration conf, String clusterId, SocketFactory factory,
1071 SocketAddress localAddr) {
1072 super(conf, clusterId, localAddr);
1073
1074 this.socketFactory = factory;
1075 this.connections = new PoolMap<ConnectionId, Connection>(getPoolType(conf), getPoolSize(conf));
1076 this.failedServers = new FailedServers(conf);
1077 }
1078
1079
1080
1081
1082
1083
1084 public RpcClientImpl(Configuration conf, String clusterId) {
1085 this(conf, clusterId, NetUtils.getDefaultSocketFactory(conf), null);
1086 }
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097 public RpcClientImpl(Configuration conf, String clusterId, SocketAddress localAddr) {
1098 this(conf, clusterId, NetUtils.getDefaultSocketFactory(conf), localAddr);
1099 }
1100
1101
1102
1103 @Override
1104 public void close() {
1105 if (LOG.isDebugEnabled()) LOG.debug("Stopping rpc client");
1106 if (!running.compareAndSet(true, false)) return;
1107
1108
1109 synchronized (connections) {
1110 for (Connection conn : connections.values()) {
1111 conn.interrupt();
1112 }
1113 }
1114
1115
1116 while (!connections.isEmpty()) {
1117 try {
1118 Thread.sleep(100);
1119 } catch (InterruptedException e) {
1120 LOG.info("Interrupted while stopping the client. We still have " + connections.size() +
1121 " connections.");
1122 Thread.currentThread().interrupt();
1123 return;
1124 }
1125 }
1126 }
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140 @Override
1141 protected Pair<Message, CellScanner> call(PayloadCarryingRpcController pcrc, MethodDescriptor md,
1142 Message param, Message returnType, User ticket, InetSocketAddress addr)
1143 throws IOException, InterruptedException {
1144 if (pcrc == null) {
1145 pcrc = new PayloadCarryingRpcController();
1146 }
1147 CellScanner cells = pcrc.cellScanner();
1148
1149 final Call call = new Call(this.callIdCnt.getAndIncrement(), md, param, cells, returnType,
1150 pcrc.getCallTimeout());
1151
1152 final Connection connection = getConnection(ticket, call, addr);
1153
1154 final CallFuture cts;
1155 if (connection.callSender != null) {
1156 cts = connection.callSender.sendCall(call, pcrc.getPriority(), Trace.currentSpan());
1157 pcrc.notifyOnCancel(new RpcCallback<Object>() {
1158 @Override
1159 public void run(Object parameter) {
1160 connection.callSender.remove(cts);
1161 }
1162 });
1163 if (pcrc.isCanceled()) {
1164
1165 call.callComplete();
1166 return new Pair<Message, CellScanner>(call.response, call.cells);
1167 }
1168 } else {
1169 cts = null;
1170 connection.tracedWriteRequest(call, pcrc.getPriority(), Trace.currentSpan());
1171 }
1172
1173 while (!call.done) {
1174 if (call.checkAndSetTimeout()) {
1175 if (cts != null) connection.callSender.remove(cts);
1176 break;
1177 }
1178 if (connection.shouldCloseConnection.get()) {
1179 throw new ConnectionClosingException("Call id=" + call.id +
1180 " on server " + addr + " aborted: connection is closing");
1181 }
1182 try {
1183 synchronized (call) {
1184 if (call.done) break;
1185 call.wait(Math.min(call.remainingTime(), 1000) + 1);
1186 }
1187 } catch (InterruptedException e) {
1188 call.setException(new InterruptedIOException());
1189 if (cts != null) connection.callSender.remove(cts);
1190 throw e;
1191 }
1192 }
1193
1194 if (call.error != null) {
1195 if (call.error instanceof RemoteException) {
1196 call.error.fillInStackTrace();
1197 throw call.error;
1198 }
1199
1200 throw wrapException(addr, call.error);
1201 }
1202
1203 return new Pair<Message, CellScanner>(call.response, call.cells);
1204 }
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219 protected IOException wrapException(InetSocketAddress addr,
1220 IOException exception) {
1221 if (exception instanceof ConnectException) {
1222
1223 return (ConnectException)new ConnectException(
1224 "Call to " + addr + " failed on connection exception: " + exception).initCause(exception);
1225 } else if (exception instanceof SocketTimeoutException) {
1226 return (SocketTimeoutException)new SocketTimeoutException("Call to " + addr +
1227 " failed because " + exception).initCause(exception);
1228 } else if (exception instanceof ConnectionClosingException){
1229 return (ConnectionClosingException) new ConnectionClosingException(
1230 "Call to " + addr + " failed on local exception: " + exception).initCause(exception);
1231 } else {
1232 return (IOException)new IOException("Call to " + addr + " failed on local exception: " +
1233 exception).initCause(exception);
1234 }
1235 }
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245 @Override
1246 public void cancelConnections(ServerName sn) {
1247 synchronized (connections) {
1248 for (Connection connection : connections.values()) {
1249 if (connection.isAlive() &&
1250 connection.getRemoteAddress().getPort() == sn.getPort() &&
1251 connection.getRemoteAddress().getHostName().equals(sn.getHostname())) {
1252 LOG.info("The server on " + sn.toString() +
1253 " is dead - stopping the connection " + connection.remoteId);
1254 connection.interrupt();
1255
1256 }
1257 }
1258 }
1259 }
1260
1261
1262
1263
1264
1265 protected Connection getConnection(User ticket, Call call, InetSocketAddress addr)
1266 throws IOException {
1267 if (!running.get()) throw new StoppedRpcClientException();
1268 Connection connection;
1269 ConnectionId remoteId =
1270 new ConnectionId(ticket, call.md.getService().getName(), addr);
1271 synchronized (connections) {
1272 connection = connections.get(remoteId);
1273 if (connection == null) {
1274 connection = createConnection(remoteId, this.codec, this.compressor);
1275 connections.put(remoteId, connection);
1276 }
1277 }
1278
1279 return connection;
1280 }
1281 }