View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
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   * Does RPC against a cluster.  Manages connections per regionserver in the cluster.
100  * <p>See HBaseServer
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); // if client runs
109 
110   protected final FailedServers failedServers;
111 
112   protected final SocketFactory socketFactory;           // how to create sockets
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    * Creates a connection. Can be overridden by a subclass for testing.
125    * @param remoteId - the ConnectionId to use for the connection creation.
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    * see {@link RpcClientImpl.Connection.CallSender}
135    */
136   private static class CallFuture {
137     final Call call;
138     final int priority;
139     final Span span;
140 
141     // We will use this to stop the writer
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   /** Thread that reads responses and notifies callers.  Each connection owns a
152    * socket connected to a remote address.  Calls are multiplexed through this
153    * socket: responses may be delivered out of order. */
154   protected class Connection extends Thread {
155     private ConnectionHeader header;              // connection header
156     protected ConnectionId remoteId;
157     protected Socket socket = null;                 // connected socket
158     protected DataInputStream in;
159     protected DataOutputStream out;
160     private Object outLock = new Object();
161     private InetSocketAddress server;             // server ip:port
162     private String serverPrincipal;  // server's krb5 principal name
163     private AuthMethod authMethod; // authentication method
164     private boolean useSasl;
165     private Token<? extends TokenIdentifier> token;
166     private HBaseSaslRpcClient saslRpcClient;
167     private int reloginMaxBackoff; // max pause before relogin on sasl failure
168     private final Codec codec;
169     private final CompressionCodec compressor;
170 
171     // currently active calls
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      * If the client wants to interrupt its calls easily (i.e. call Thread#interrupt),
181      *  it gets into a java issue: an interruption during a write closes the socket/channel.
182      * A way to avoid this is to use a different thread for writing. This way, on interruptions,
183      *  we either cancel the writes or ignore the answer if the write is already done, but we
184      *  don't stop the write in the middle.
185      * This adds a thread per region server in the client, so it's kept as an option.
186      * <p>
187      * The implementation is simple: the client threads adds their call to the queue, and then
188      *  wait for an answer. The CallSender blocks on the queue, and writes the calls one
189      *  after the other. On interruption, the client cancels its call. The CallSender checks that
190      *  the call has not been canceled before writing it.
191      * </p>
192      * When the connection closes, all the calls not yet sent are dismissed. The client thread
193      *  is notified with an appropriate exception, as if the call was already sent but the answer
194      *  not yet received.
195      * </p>
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(); // We check after the put, to be sure that the call we added won't stay
209                        //  in the list while the cleanup was already done.
210         return cts;
211       }
212 
213       @Override
214       public void close(){
215         assert shouldCloseConnection.get();
216         callsToWrite.offer(CallFuture.DEATH_PILL);
217         // We don't care if we can't add the death pill to the queue: the writer
218         //  won't be blocked in the 'take', as its queue is full.
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         // By removing the call from the expected call list, we make the list smaller, but
232         //  it means as well that we don't know how many calls we cancelled.
233         calls.remove(cts.call.id);
234         cts.call.callComplete();
235       }
236 
237       /**
238        * Reads the call from the queue, write them on the socket.
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        * Cleans the call not yet sent when we finish.
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         // Don't send user for token auth
381         return null;
382       }
383       UserInformation.Builder userInfoPB = UserInformation.newBuilder();
384       if (authMethod == AuthMethod.KERBEROS) {
385         // Send effective user for Kerberos auth
386         userInfoPB.setEffectiveUser(ugi.getUserName());
387       } else if (authMethod == AuthMethod.SIMPLE) {
388         //Send both effective user and real user for simple auth
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           /* The max number of retries is 45,
413            * which amounts to 20s*45 = 15 minutes retries.
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       // close the current connection
428       try {
429         if (socket.getOutputStream() != null) {
430           socket.getOutputStream().close();
431         }
432       } catch (IOException ignored) {  // Can happen if the socket is already closed
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) {  // Can happen if the socket is already closed
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) {  // Can happen if the socket is already closed
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       // set socket to null so that the next call to setupIOstreams
456       // can start the process of connect all over again.
457       socket = null;
458     }
459 
460     /**
461      *  Handle connection failures
462      *
463      * If the current number of retries is equal to the max number of retries,
464      * stop retrying and throw the exception; Otherwise backoff N seconds and
465      * try connecting again.
466      *
467      * This Method is only called from inside setupIOstreams(), which is
468      * synchronized. Hence the sleep is synchronized; the locks will be retained.
469      *
470      * @param curRetries current number of retries
471      * @param maxRetries max number of retries allowed
472      * @param ioe failure reason
473      * @throws IOException if max number of retries is reached
474      */
475     private void handleConnectionFailure(int curRetries, int maxRetries, IOException ioe)
476     throws IOException {
477       closeConnection();
478 
479       // throw the exception if the maximum number of retries is reached
480       if (curRetries >= maxRetries || ExceptionUtil.isInterrupt(ioe)) {
481         throw ioe;
482       }
483 
484       // otherwise back off and retry
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      * @throws IOException if the connection is not open.
498      */
499     private void checkIsOpen() throws IOException {
500       if (shouldCloseConnection.get()) {
501         throw new ConnectionClosingException(getName() + " is closing");
502       }
503     }
504 
505     /* wait till someone signals us to start reading RPC response or
506      * it is idle too long, it is marked as to be closed,
507      * or the client is marked as not running.
508      *
509      * @return true if it is time to read a response; false otherwise.
510      */
511     protected synchronized boolean waitForWork() throws InterruptedException {
512       // beware of the concurrent access to the calls list: we can add calls, but as well
513       //  remove them.
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           // shouldCloseConnection can be set to true by a parallel thread here. The caller
528           //  will need to check anyway.
529           return true;
530         }
531 
532         if (EnvironmentEdgeManager.currentTime() >= waitUntil) {
533           // Connection is idle.
534           // We expect the number of calls to be zero here, but actually someone can
535           //  adds a call at the any moment, as there is no synchronization between this task
536           //  and adding new calls. It's not a big issue, but it will get an exception.
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()) { // Wait here for work - read or close connection
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           //Make sure user logged in using Kerberos either keytab or TGT
598           loginUser.hasKerberosCredentials() &&
599           // relogin only in case it is the login user (e.g. JT)
600           // or superuser (like oozie).
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      * If multiple clients with the same principal try to connect
614      * to the same server at the same time, the server assumes a
615      * replay attack is in progress. This is a feature of kerberos.
616      * In order to work around this, what is done is that the client
617      * backs off randomly and tries to initiate the connection
618      * again.
619      * The other problem is to do with ticket expiry. To handle that,
620      * a relogin is attempted.
621      * <p>
622      * The retry logic is governed by the {@link #shouldAuthenticateOverKrb}
623      * method. In case when the user doesn't have valid credentials, we don't
624      * need to retry (from cache or ticket). In such cases, it is prudent to
625      * throw a runtime exception when we receive a SaslException from the
626      * underlying authentication implementation, so there is no retry from
627      * other high level (for eg, HCM or HBaseAdmin).
628      * </p>
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               //try re-login
646               if (UserGroupInformation.isLoginKeytabBased()) {
647                 UserGroupInformation.getLoginUser().reloginFromKeytab();
648               } else {
649                 UserGroupInformation.getLoginUser().reloginFromTicketCache();
650               }
651               disposeSasl();
652               //have granularity of milliseconds
653               //we are sleeping with the Connection lock held but since this
654               //connection instance is being used for connecting to the server
655               //in question, it is okay
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         // The connection is already available. Perfect.
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           // This creates a socket with a write timeout. This timeout cannot be changed.
717           OutputStream outStream = NetUtils.getOutputStream(socket, writeTO);
718           // Write out the preamble -- MAGIC, version, and auth to use.
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               // Sasl connect is successful. Let's set up Sasl i/o streams.
748               inStream = saslRpcClient.getInputStream(inStream);
749               outStream = saslRpcClient.getOutputStream(outStream);
750             } else {
751               // fall back to simple auth because server told us so.
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           // Now write out the connection header
761           writeConnectionHeader();
762 
763           // start the receiver thread after the socket connection has been set up
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             // probably the hbase hadoop version does not match the running hadoop version
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      * Write the RPC header: <MAGIC WORD -- 'HBas'> <ONEBYTE_VERSION> <ONEBYTE_AUTH_TYPE>
788      */
789     private void writeConnectionHeaderPreamble(OutputStream outStream) throws IOException {
790       // Assemble the preamble up in a buffer first and then send it.  Writing individual elements,
791       // they are getting sent across piecemeal according to wireshark and then server is messing
792       // up the reading on occasion (the passed in stream is not buffered yet).
793 
794       // Preamble is six bytes -- 'HBas' + VERSION + AUTH_CODE
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      * Write the connection header.
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     /** Close the connection. */
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       // release the resources
823       // first thing to do;take the connection out of the connection list
824       synchronized (connections) {
825         connections.removeValue(remoteId, this);
826       }
827 
828       // close the streams and therefore the socket
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       // log the info
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      * Initiates a call by sending the parameter to the remote server.
862      * Note: this is not called from the Connection thread, but by other
863      * threads.
864      * @see #readResponse()
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       // Only pass priority if there one.  Let zero be same as no priority.
882       if (priority != 0) builder.setPriority(priority);
883       RequestHeader header = builder.build();
884 
885       setupIOstreams();
886 
887       // Now we're going to write the call. We take the lock, then check that the connection
888       //  is still valid, and, if so we do the write to the socket. If the write fails, we don't
889       //  know where we stand, we have to close the connection.
890       checkIsOpen();
891       IOException writeException = null;
892       synchronized (this.outLock) {
893         if (Thread.interrupted()) throw new InterruptedIOException();
894 
895         calls.put(call.id, call); // We put first as we don't want the connection to become idle.
896         checkIsOpen(); // Now we're checking that it didn't became idle in between.
897 
898         try {
899           IPCUtil.write(this.out, header, call.param, cellBlock);
900         } catch (IOException e) {
901           // We set the value inside the synchronized block, this way the next in line
902           //  won't even try to write
903           shouldCloseConnection.set(true);
904           writeException = e;
905           interrupt();
906         }
907       }
908 
909       // We added a call, and may be started the connection close. In both cases, we
910       //  need to notify the reader.
911       synchronized (this) {
912         notifyAll();
913       }
914 
915       // Now that we notified, we can rethrow the exception if any. Otherwise we're good.
916       if (writeException != null) throw writeException;
917     }
918 
919     /* Receive a response.
920      * Because only one receiver, so no synchronization on in.
921      */
922     protected void readResponse() {
923       if (shouldCloseConnection.get()) return;
924       Call call = null;
925       boolean expectedCall = false;
926       try {
927         // See HBaseServer.Call.setResponse for where we write out the response.
928         // Total size of the response.  Unused.  But have to read it in anyways.
929         int totalSize = in.readInt();
930 
931         // Read the header
932         ResponseHeader responseHeader = ResponseHeader.parseDelimitedFrom(in);
933         int id = responseHeader.getCallId();
934         call = calls.remove(id); // call.done have to be set before leaving this method
935         expectedCall = (call != null && !call.done);
936         if (!expectedCall) {
937           // So we got a response for which we have no corresponding 'call' here on the client-side.
938           // We probably timed out waiting, cleaned up all references, and now the server decides
939           // to return a response.  There is nothing we can do w/ the response at this stage. Clean
940           // out the wire of the response so its out of the way and we can get other responses on
941           // this connection.
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           // Clean up open calls but don't treat this as a fatal condition,
974           // since we expect certain responses to not make it by the specified
975           // {@link ConnectionId#rpcTimeout}.
976           if (LOG.isTraceEnabled()) LOG.trace("ignored", e);
977         } else {
978           // Treat this as a fatal condition and close this connection
979           markClosed(e);
980         }
981       } finally {
982         cleanupCalls(false);
983       }
984     }
985 
986     /**
987      * @return True if the exception is a fatal connection exception.
988      */
989     private boolean isFatalConnectionException(final ExceptionResponse e) {
990       return e.getExceptionClassName().
991         equals(FatalConnectionException.class.getName());
992     }
993 
994     /**
995      * @param e exception to be wrapped
996      * @return RemoteException made from passed <code>e</code>
997      */
998     private RemoteException createRemoteException(final ExceptionResponse e) {
999       String innerExceptionClassName = e.getExceptionClassName();
1000       boolean doNotRetry = e.getDoNotRetry();
1001       return e.hasHostname()?
1002         // If a hostname then add it to the RemoteWithExtrasException
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      * Cleanup the calls older than a given timeout, in milli seconds.
1026      * @param allCalls true for all calls, false for only the calls in timeout
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           // To catch the calls without timeout that were cancelled.
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           // We expect the call to be ordered by timeout. It may not be the case, but stopping
1045           //  at the first valid call allows to be sure that we still have something to do without
1046           //  spending too much time by reading the full list.
1047           break;
1048         }
1049       }
1050     }
1051   }
1052 
1053   /**
1054    * Construct an IPC cluster client whose values are of the {@link Message} class.
1055    * @param conf configuration
1056    * @param clusterId the cluster id
1057    * @param factory socket factory
1058    */
1059   RpcClientImpl(Configuration conf, String clusterId, SocketFactory factory) {
1060     this(conf, clusterId, factory, null);
1061   }
1062 
1063   /**
1064    * Construct an IPC cluster client whose values are of the {@link Message} class.
1065    * @param conf configuration
1066    * @param clusterId the cluster id
1067    * @param factory socket factory
1068    * @param localAddr client socket bind address
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    * Construct an IPC client for the cluster <code>clusterId</code> with the default SocketFactory
1081    * @param conf configuration
1082    * @param clusterId the cluster id
1083    */
1084   public RpcClientImpl(Configuration conf, String clusterId) {
1085     this(conf, clusterId, NetUtils.getDefaultSocketFactory(conf), null);
1086   }
1087 
1088   /**
1089    * Construct an IPC client for the cluster <code>clusterId</code> with the default SocketFactory
1090    *
1091    * This method is called with reflection by the RpcClientFactory to create an instance
1092    *
1093    * @param conf configuration
1094    * @param clusterId the cluster id
1095    * @param localAddr client socket bind address.
1096    */
1097   public RpcClientImpl(Configuration conf, String clusterId, SocketAddress localAddr) {
1098     this(conf, clusterId, NetUtils.getDefaultSocketFactory(conf), localAddr);
1099   }
1100 
1101   /** Stop all threads related to this client.  No further calls may be made
1102    * using this client. */
1103   @Override
1104   public void close() {
1105     if (LOG.isDebugEnabled()) LOG.debug("Stopping rpc client");
1106     if (!running.compareAndSet(true, false)) return;
1107 
1108     // wake up all connections
1109     synchronized (connections) {
1110       for (Connection conn : connections.values()) {
1111         conn.interrupt();
1112       }
1113     }
1114 
1115     // wait until all connections are closed
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   /** Make a call, passing <code>param</code>, to the IPC server running at
1129    * <code>address</code> which is servicing the <code>protocol</code> protocol,
1130    * with the <code>ticket</code> credentials, returning the value.
1131    * Throws exceptions if there are network problems or if the remote code
1132    * threw an exception.
1133    * @param ticket Be careful which ticket you pass. A new user will mean a new Connection.
1134    *          {@link UserProvider#getCurrent()} makes a new instance of User each time so will be a
1135    *          new Connection each time.
1136    * @return A pair with the Message response and the Cell data (if any).
1137    * @throws InterruptedException
1138    * @throws IOException
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           // To finish if the call was cancelled before we set the notification (race condition)
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       // local exception
1200       throw wrapException(addr, call.error);
1201     }
1202 
1203     return new Pair<Message, CellScanner>(call.response, call.cells);
1204   }
1205 
1206 
1207   /**
1208    * Take an IOException and the address we were trying to connect to
1209    * and return an IOException with the input exception as the cause.
1210    * The new exception provides the stack trace of the place where
1211    * the exception is thrown and some extra diagnostics information.
1212    * If the exception is ConnectException or SocketTimeoutException,
1213    * return a new one of the same type; Otherwise return an IOException.
1214    *
1215    * @param addr target address
1216    * @param exception the relevant exception
1217    * @return an exception to throw
1218    */
1219   protected IOException wrapException(InetSocketAddress addr,
1220                                          IOException exception) {
1221     if (exception instanceof ConnectException) {
1222       //connection refused; include the host:port in the error
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    * Interrupt the connections to the given ip:port server. This should be called if the server
1239    *  is known as actually dead. This will not prevent current operation to be retried, and,
1240    *  depending on their own behavior, they may retry on the same server. This can be a feature,
1241    *  for example at startup. In any case, they're likely to get connection refused (if the
1242    *  process died) or no route to host: i.e. their next retries should be faster and with a
1243    *  safe exception.
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(); // We're interrupting a Reader. It means we want it to finish.
1255                                   // This will close the connection as well.
1256         }
1257       }
1258     }
1259   }
1260 
1261   /**
1262    *  Get a connection from the pool, or create a new one and add it to the
1263    * pool. Connections to a given host/port are reused.
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 }