View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.ipc;
20  
21  import com.google.common.annotations.VisibleForTesting;
22  import com.google.protobuf.BlockingRpcChannel;
23  import com.google.protobuf.Descriptors;
24  import com.google.protobuf.Message;
25  import com.google.protobuf.RpcController;
26  import com.google.protobuf.ServiceException;
27  
28  import java.io.IOException;
29  import java.net.ConnectException;
30  import java.net.InetSocketAddress;
31  import java.net.SocketAddress;
32  import java.net.SocketTimeoutException;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.hbase.CellScanner;
38  import org.apache.hadoop.hbase.HConstants;
39  import org.apache.hadoop.hbase.ServerName;
40  import org.apache.hadoop.hbase.classification.InterfaceAudience;
41  import org.apache.hadoop.hbase.codec.Codec;
42  import org.apache.hadoop.hbase.codec.KeyValueCodec;
43  import org.apache.hadoop.hbase.exceptions.ConnectionClosingException;
44  import org.apache.hadoop.hbase.security.User;
45  import org.apache.hadoop.hbase.security.UserProvider;
46  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
47  import org.apache.hadoop.hbase.util.Pair;
48  import org.apache.hadoop.hbase.util.PoolMap;
49  import org.apache.hadoop.io.compress.CompressionCodec;
50  
51  /**
52   * Provides the basics for a RpcClient implementation like configuration and Logging.
53   */
54  @InterfaceAudience.Private
55  public abstract class AbstractRpcClient implements RpcClient {
56    public static final Log LOG = LogFactory.getLog(AbstractRpcClient.class);
57  
58    protected final Configuration conf;
59    protected String clusterId;
60    protected final SocketAddress localAddr;
61  
62    protected UserProvider userProvider;
63    protected final IPCUtil ipcUtil;
64  
65    protected final int minIdleTimeBeforeClose; // if the connection is idle for more than this
66    // time (in ms), it will be closed at any moment.
67    protected final int maxRetries; //the max. no. of retries for socket connections
68    protected final long failureSleep; // Time to sleep before retry on failure.
69    protected final boolean tcpNoDelay; // if T then disable Nagle's Algorithm
70    protected final boolean tcpKeepAlive; // if T then use keepalives
71    protected final Codec codec;
72    protected final CompressionCodec compressor;
73    protected final boolean fallbackAllowed;
74  
75    protected final int connectTO;
76    protected final int readTO;
77    protected final int writeTO;
78  
79    /**
80     * Construct an IPC client for the cluster <code>clusterId</code>
81     *
82     * @param conf configuration
83     * @param clusterId the cluster id
84     * @param localAddr client socket bind address.
85     */
86    public AbstractRpcClient(Configuration conf, String clusterId, SocketAddress localAddr) {
87      this.userProvider = UserProvider.instantiate(conf);
88      this.localAddr = localAddr;
89      this.tcpKeepAlive = conf.getBoolean("hbase.ipc.client.tcpkeepalive", true);
90      this.clusterId = clusterId != null ? clusterId : HConstants.CLUSTER_ID_DEFAULT;
91      this.failureSleep = conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
92          HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
93      this.maxRetries = conf.getInt("hbase.ipc.client.connect.max.retries", 0);
94      this.tcpNoDelay = conf.getBoolean("hbase.ipc.client.tcpnodelay", true);
95      this.ipcUtil = new IPCUtil(conf);
96  
97      this.minIdleTimeBeforeClose = conf.getInt(IDLE_TIME, 120000); // 2 minutes
98      this.conf = conf;
99      this.codec = getCodec();
100     this.compressor = getCompressor(conf);
101     this.fallbackAllowed = conf.getBoolean(IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_KEY,
102         IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_DEFAULT);
103     this.connectTO = conf.getInt(SOCKET_TIMEOUT_CONNECT, DEFAULT_SOCKET_TIMEOUT_CONNECT);
104     this.readTO = conf.getInt(SOCKET_TIMEOUT_READ, DEFAULT_SOCKET_TIMEOUT_READ);
105     this.writeTO = conf.getInt(SOCKET_TIMEOUT_WRITE, DEFAULT_SOCKET_TIMEOUT_WRITE);
106 
107     // login the server principal (if using secure Hadoop)
108     if (LOG.isDebugEnabled()) {
109       LOG.debug("Codec=" + this.codec + ", compressor=" + this.compressor +
110           ", tcpKeepAlive=" + this.tcpKeepAlive +
111           ", tcpNoDelay=" + this.tcpNoDelay +
112           ", connectTO=" + this.connectTO +
113           ", readTO=" + this.readTO +
114           ", writeTO=" + this.writeTO +
115           ", minIdleTimeBeforeClose=" + this.minIdleTimeBeforeClose +
116           ", maxRetries=" + this.maxRetries +
117           ", fallbackAllowed=" + this.fallbackAllowed +
118           ", bind address=" + (this.localAddr != null ? this.localAddr : "null"));
119     }
120   }
121 
122   @VisibleForTesting
123   public static String getDefaultCodec(final Configuration c) {
124     // If "hbase.client.default.rpc.codec" is empty string -- you can't set it to null because
125     // Configuration will complain -- then no default codec (and we'll pb everything).  Else
126     // default is KeyValueCodec
127     return c.get(DEFAULT_CODEC_CLASS, KeyValueCodec.class.getCanonicalName());
128   }
129 
130   /**
131    * Encapsulate the ugly casting and RuntimeException conversion in private method.
132    * @return Codec to use on this client.
133    */
134   Codec getCodec() {
135     // For NO CODEC, "hbase.client.rpc.codec" must be configured with empty string AND
136     // "hbase.client.default.rpc.codec" also -- because default is to do cell block encoding.
137     String className = conf.get(HConstants.RPC_CODEC_CONF_KEY, getDefaultCodec(this.conf));
138     if (className == null || className.length() == 0) return null;
139     try {
140       return (Codec)Class.forName(className).newInstance();
141     } catch (Exception e) {
142       throw new RuntimeException("Failed getting codec " + className, e);
143     }
144   }
145 
146   /**
147    * Encapsulate the ugly casting and RuntimeException conversion in private method.
148    * @param conf configuration
149    * @return The compressor to use on this client.
150    */
151   private static CompressionCodec getCompressor(final Configuration conf) {
152     String className = conf.get("hbase.client.rpc.compressor", null);
153     if (className == null || className.isEmpty()) return null;
154     try {
155         return (CompressionCodec)Class.forName(className).newInstance();
156     } catch (Exception e) {
157       throw new RuntimeException("Failed getting compressor " + className, e);
158     }
159   }
160 
161   /**
162    * Return the pool type specified in the configuration, which must be set to
163    * either {@link org.apache.hadoop.hbase.util.PoolMap.PoolType#RoundRobin} or
164    * {@link org.apache.hadoop.hbase.util.PoolMap.PoolType#ThreadLocal},
165    * otherwise default to the former.
166    *
167    * For applications with many user threads, use a small round-robin pool. For
168    * applications with few user threads, you may want to try using a
169    * thread-local pool. In any case, the number of {@link org.apache.hadoop.hbase.ipc.RpcClient}
170    * instances should not exceed the operating system's hard limit on the number of
171    * connections.
172    *
173    * @param config configuration
174    * @return either a {@link org.apache.hadoop.hbase.util.PoolMap.PoolType#RoundRobin} or
175    *         {@link org.apache.hadoop.hbase.util.PoolMap.PoolType#ThreadLocal}
176    */
177   protected static PoolMap.PoolType getPoolType(Configuration config) {
178     return PoolMap.PoolType
179         .valueOf(config.get(HConstants.HBASE_CLIENT_IPC_POOL_TYPE), PoolMap.PoolType.RoundRobin,
180             PoolMap.PoolType.ThreadLocal);
181   }
182 
183   /**
184    * Return the pool size specified in the configuration, which is applicable only if
185    * the pool type is {@link org.apache.hadoop.hbase.util.PoolMap.PoolType#RoundRobin}.
186    *
187    * @param config configuration
188    * @return the maximum pool size
189    */
190   protected static int getPoolSize(Configuration config) {
191     return config.getInt(HConstants.HBASE_CLIENT_IPC_POOL_SIZE, 1);
192   }
193 
194   /**
195    * Make a blocking call. Throws exceptions if there are network problems or if the remote code
196    * threw an exception.
197    *
198    * @param ticket Be careful which ticket you pass. A new user will mean a new Connection.
199    *               {@link UserProvider#getCurrent()} makes a new instance of User each time so
200    *               will be a
201    *               new Connection each time.
202    * @return A pair with the Message response and the Cell data (if any).
203    */
204   Message callBlockingMethod(Descriptors.MethodDescriptor md, PayloadCarryingRpcController pcrc,
205       Message param, Message returnType, final User ticket, final InetSocketAddress isa)
206       throws ServiceException {
207     if (pcrc == null) {
208       pcrc = new PayloadCarryingRpcController();
209     }
210 
211     long startTime = 0;
212     if (LOG.isTraceEnabled()) {
213       startTime = EnvironmentEdgeManager.currentTime();
214     }
215     Pair<Message, CellScanner> val;
216     try {
217       val = call(pcrc, md, param, returnType, ticket, isa);
218       // Shove the results into controller so can be carried across the proxy/pb service void.
219       pcrc.setCellScanner(val.getSecond());
220 
221       if (LOG.isTraceEnabled()) {
222         long callTime = EnvironmentEdgeManager.currentTime() - startTime;
223         LOG.trace("Call: " + md.getName() + ", callTime: " + callTime + "ms");
224       }
225       return val.getFirst();
226     } catch (Throwable e) {
227       throw new ServiceException(e);
228     }
229   }
230 
231   /**
232    * Make a call, passing <code>param</code>, to the IPC server running at
233    * <code>address</code> which is servicing the <code>protocol</code> protocol,
234    * with the <code>ticket</code> credentials, returning the value.
235    * Throws exceptions if there are network problems or if the remote code
236    * threw an exception.
237    *
238    * @param ticket Be careful which ticket you pass. A new user will mean a new Connection.
239    *               {@link UserProvider#getCurrent()} makes a new instance of User each time so
240    *               will be a
241    *               new Connection each time.
242    * @return A pair with the Message response and the Cell data (if any).
243    * @throws InterruptedException
244    * @throws java.io.IOException
245    */
246   protected abstract Pair<Message, CellScanner> call(PayloadCarryingRpcController pcrc,
247       Descriptors.MethodDescriptor md, Message param, Message returnType, User ticket,
248       InetSocketAddress isa) throws IOException, InterruptedException;
249 
250   @Override
251   public BlockingRpcChannel createBlockingRpcChannel(final ServerName sn, final User ticket,
252       int defaultOperationTimeout) {
253     return new BlockingRpcChannelImplementation(this, sn, ticket, defaultOperationTimeout);
254   }
255 
256   /**
257    * Takes an Exception and the address we were trying to connect to and return an IOException with
258    * the input exception as the cause. The new exception provides the stack trace of the place where
259    * the exception is thrown and some extra diagnostics information. If the exception is
260    * ConnectException or SocketTimeoutException, return a new one of the same type; Otherwise return
261    * an IOException.
262    * @param addr target address
263    * @param exception the relevant exception
264    * @return an exception to throw
265    */
266   protected IOException wrapException(InetSocketAddress addr, Exception exception) {
267     if (exception instanceof ConnectException) {
268       // connection refused; include the host:port in the error
269       return (ConnectException) new ConnectException("Call to " + addr
270           + " failed on connection exception: " + exception).initCause(exception);
271     } else if (exception instanceof SocketTimeoutException) {
272       return (SocketTimeoutException) new SocketTimeoutException("Call to " + addr
273           + " failed because " + exception).initCause(exception);
274     } else if (exception instanceof ConnectionClosingException) {
275       return (ConnectionClosingException) new ConnectionClosingException("Call to " + addr
276           + " failed on local exception: " + exception).initCause(exception);
277     } else {
278       return (IOException) new IOException("Call to " + addr + " failed on local exception: "
279           + exception).initCause(exception);
280     }
281   }
282 
283   /**
284    * Blocking rpc channel that goes via hbase rpc.
285    */
286   @VisibleForTesting
287   public static class BlockingRpcChannelImplementation implements BlockingRpcChannel {
288     private final InetSocketAddress isa;
289     private final AbstractRpcClient rpcClient;
290     private final User ticket;
291     private final int channelOperationTimeout;
292 
293     /**
294      * @param channelOperationTimeout - the default timeout when no timeout is given
295      */
296     protected BlockingRpcChannelImplementation(final AbstractRpcClient rpcClient,
297         final ServerName sn, final User ticket, int channelOperationTimeout) {
298       this.isa = new InetSocketAddress(sn.getHostname(), sn.getPort());
299       this.rpcClient = rpcClient;
300       this.ticket = ticket;
301       this.channelOperationTimeout = channelOperationTimeout;
302     }
303 
304     @Override
305     public Message callBlockingMethod(Descriptors.MethodDescriptor md, RpcController controller,
306         Message param, Message returnType) throws ServiceException {
307       PayloadCarryingRpcController pcrc;
308       if (controller != null) {
309         pcrc = (PayloadCarryingRpcController) controller;
310         if (!pcrc.hasCallTimeout()) {
311           pcrc.setCallTimeout(channelOperationTimeout);
312         }
313       } else {
314         pcrc = new PayloadCarryingRpcController();
315         pcrc.setCallTimeout(channelOperationTimeout);
316       }
317 
318       return this.rpcClient.callBlockingMethod(md, pcrc, param, returnType, this.ticket, this.isa);
319     }
320   }
321 }