1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.ipc;
20
21 import static org.apache.hadoop.hbase.ipc.IPCUtil.toIOE;
22 import static org.apache.hadoop.hbase.ipc.IPCUtil.wrapException;
23
24 import com.google.common.annotations.VisibleForTesting;
25 import com.google.common.base.Preconditions;
26 import com.google.common.cache.CacheBuilder;
27 import com.google.common.cache.CacheLoader;
28 import com.google.common.cache.LoadingCache;
29 import com.google.protobuf.BlockingRpcChannel;
30 import com.google.protobuf.Descriptors;
31 import com.google.protobuf.Message;
32 import com.google.protobuf.RpcCallback;
33 import com.google.protobuf.RpcChannel;
34 import com.google.protobuf.RpcController;
35 import com.google.protobuf.ServiceException;
36
37 import io.netty.util.HashedWheelTimer;
38
39 import java.io.IOException;
40 import java.net.InetSocketAddress;
41 import java.net.SocketAddress;
42 import java.net.UnknownHostException;
43 import java.util.Collection;
44 import java.util.HashMap;
45 import java.util.Map;
46 import java.util.concurrent.Executors;
47 import java.util.concurrent.ScheduledExecutorService;
48 import java.util.concurrent.ScheduledFuture;
49 import java.util.concurrent.TimeUnit;
50 import java.util.concurrent.atomic.AtomicInteger;
51
52 import org.apache.commons.logging.Log;
53 import org.apache.commons.logging.LogFactory;
54 import org.apache.hadoop.conf.Configuration;
55 import org.apache.hadoop.hbase.HConstants;
56 import org.apache.hadoop.hbase.ServerName;
57 import org.apache.hadoop.hbase.classification.InterfaceAudience;
58 import org.apache.hadoop.hbase.client.MetricsConnection;
59 import org.apache.hadoop.hbase.codec.Codec;
60 import org.apache.hadoop.hbase.codec.KeyValueCodec;
61 import org.apache.hadoop.hbase.protobuf.generated.AuthenticationProtos.TokenIdentifier.Kind;
62 import org.apache.hadoop.hbase.security.User;
63 import org.apache.hadoop.hbase.security.UserProvider;
64 import org.apache.hadoop.hbase.security.token.AuthenticationTokenSelector;
65 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
66 import org.apache.hadoop.hbase.util.PoolMap;
67 import org.apache.hadoop.hbase.util.Threads;
68 import org.apache.hadoop.io.compress.CompressionCodec;
69 import org.apache.hadoop.ipc.RemoteException;
70 import org.apache.hadoop.security.token.TokenIdentifier;
71 import org.apache.hadoop.security.token.TokenSelector;
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93 @InterfaceAudience.Private
94 public abstract class AbstractRpcClient<T extends RpcConnection> implements RpcClient {
95
96 public static final Log LOG = LogFactory.getLog(AbstractRpcClient.class);
97
98 protected static final HashedWheelTimer WHEEL_TIMER = new HashedWheelTimer(
99 Threads.newDaemonThreadFactory("RpcClient-timer"), 10, TimeUnit.MILLISECONDS);
100
101 private static final ScheduledExecutorService IDLE_CONN_SWEEPER = Executors
102 .newScheduledThreadPool(1, Threads.newDaemonThreadFactory("Idle-Rpc-Conn-Sweeper"));
103
104 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="MS_MUTABLE_COLLECTION_PKGPROTECT",
105 justification="the rest of the system which live in the different package can use")
106 protected final static Map<Kind, TokenSelector<? extends TokenIdentifier>> TOKEN_HANDLERS = new HashMap<>();
107
108 static {
109 TOKEN_HANDLERS.put(Kind.HBASE_AUTH_TOKEN, new AuthenticationTokenSelector());
110 }
111
112 protected boolean running = true;
113
114 protected final Configuration conf;
115 protected final String clusterId;
116 protected final SocketAddress localAddr;
117 protected final MetricsConnection metrics;
118
119 protected final UserProvider userProvider;
120 protected final CellBlockBuilder cellBlockBuilder;
121
122 protected final int minIdleTimeBeforeClose;
123
124 protected final int maxRetries;
125 protected final long failureSleep;
126 protected final boolean tcpNoDelay;
127 protected final boolean tcpKeepAlive;
128 protected final Codec codec;
129 protected final CompressionCodec compressor;
130 protected final boolean fallbackAllowed;
131
132 protected final FailedServers failedServers;
133
134 protected final int connectTO;
135 protected final int readTO;
136 protected final int writeTO;
137
138 protected final PoolMap<ConnectionId, T> connections;
139
140 private final AtomicInteger callIdCnt = new AtomicInteger(0);
141
142 private final ScheduledFuture<?> cleanupIdleConnectionTask;
143
144 private int maxConcurrentCallsPerServer;
145
146 private static final LoadingCache<InetSocketAddress, AtomicInteger> concurrentCounterCache =
147 CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.HOURS).
148 build(new CacheLoader<InetSocketAddress, AtomicInteger>() {
149 @Override public AtomicInteger load(InetSocketAddress key) throws Exception {
150 return new AtomicInteger(0);
151 }
152 });
153
154
155
156
157
158
159
160
161 public AbstractRpcClient(Configuration conf, String clusterId, SocketAddress localAddr,
162 MetricsConnection metrics) {
163 this.userProvider = UserProvider.instantiate(conf);
164 this.localAddr = localAddr;
165 this.tcpKeepAlive = conf.getBoolean("hbase.ipc.client.tcpkeepalive", true);
166 this.clusterId = clusterId != null ? clusterId : HConstants.CLUSTER_ID_DEFAULT;
167 this.failureSleep = conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
168 HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
169 this.maxRetries = conf.getInt("hbase.ipc.client.connect.max.retries", 0);
170 this.tcpNoDelay = conf.getBoolean("hbase.ipc.client.tcpnodelay", true);
171 this.cellBlockBuilder = new CellBlockBuilder(conf);
172
173 this.minIdleTimeBeforeClose = conf.getInt(IDLE_TIME, 120000);
174 this.conf = conf;
175 this.codec = getCodec();
176 this.compressor = getCompressor(conf);
177 this.fallbackAllowed = conf.getBoolean(IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_KEY,
178 IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_DEFAULT);
179 this.failedServers = new FailedServers(conf);
180 this.connectTO = conf.getInt(SOCKET_TIMEOUT_CONNECT, DEFAULT_SOCKET_TIMEOUT_CONNECT);
181 this.readTO = conf.getInt(SOCKET_TIMEOUT_READ, DEFAULT_SOCKET_TIMEOUT_READ);
182 this.writeTO = conf.getInt(SOCKET_TIMEOUT_WRITE, DEFAULT_SOCKET_TIMEOUT_WRITE);
183 this.metrics = metrics;
184 this.maxConcurrentCallsPerServer = conf.getInt(
185 HConstants.HBASE_CLIENT_PERSERVER_REQUESTS_THRESHOLD,
186 HConstants.DEFAULT_HBASE_CLIENT_PERSERVER_REQUESTS_THRESHOLD);
187
188 this.connections = new PoolMap<>(getPoolType(conf), getPoolSize(conf));
189
190 this.cleanupIdleConnectionTask = IDLE_CONN_SWEEPER.scheduleAtFixedRate(new Runnable() {
191
192 @Override
193 public void run() {
194 cleanupIdleConnections();
195 }
196 }, minIdleTimeBeforeClose, minIdleTimeBeforeClose, TimeUnit.MILLISECONDS);
197
198 if (LOG.isDebugEnabled()) {
199 LOG.debug("Codec=" + this.codec + ", compressor=" + this.compressor + ", tcpKeepAlive="
200 + this.tcpKeepAlive + ", tcpNoDelay=" + this.tcpNoDelay + ", connectTO=" + this.connectTO
201 + ", readTO=" + this.readTO + ", writeTO=" + this.writeTO + ", minIdleTimeBeforeClose="
202 + this.minIdleTimeBeforeClose + ", maxRetries=" + this.maxRetries + ", fallbackAllowed="
203 + this.fallbackAllowed + ", bind address="
204 + (this.localAddr != null ? this.localAddr : "null"));
205 }
206 }
207
208 private void cleanupIdleConnections() {
209 long closeBeforeTime = EnvironmentEdgeManager.currentTime() - minIdleTimeBeforeClose;
210 synchronized (connections) {
211 for (T conn : connections.values()) {
212
213
214
215
216 if (conn.getLastTouched() < closeBeforeTime && !conn.isActive()) {
217 LOG.info("Cleanup idle connection to " + conn.remoteId().address);
218 connections.removeValue(conn.remoteId(), conn);
219 conn.cleanupConnection();
220 }
221 }
222 }
223 }
224
225 @VisibleForTesting
226 public static String getDefaultCodec(final Configuration c) {
227
228
229
230 return c.get(DEFAULT_CODEC_CLASS, KeyValueCodec.class.getCanonicalName());
231 }
232
233
234
235
236
237 Codec getCodec() {
238
239
240 String className = conf.get(HConstants.RPC_CODEC_CONF_KEY, getDefaultCodec(this.conf));
241 if (className == null || className.length() == 0) {
242 return null;
243 }
244 try {
245 return (Codec) Class.forName(className).getDeclaredConstructor().newInstance();
246 } catch (Exception e) {
247 throw new RuntimeException("Failed getting codec " + className, e);
248 }
249 }
250
251 @Override
252 public boolean hasCellBlockSupport() {
253 return this.codec != null;
254 }
255
256
257 @VisibleForTesting
258 boolean isTcpNoDelay() {
259 return tcpNoDelay;
260 }
261
262
263
264
265
266
267 private static CompressionCodec getCompressor(final Configuration conf) {
268 String className = conf.get("hbase.client.rpc.compressor", null);
269 if (className == null || className.isEmpty()) {
270 return null;
271 }
272 try {
273 return (CompressionCodec) Class.forName(className).getDeclaredConstructor().newInstance();
274 } catch (Exception e) {
275 throw new RuntimeException("Failed getting compressor " + className, e);
276 }
277 }
278
279
280
281
282
283
284
285
286
287
288
289
290
291 private static PoolMap.PoolType getPoolType(Configuration config) {
292 return PoolMap.PoolType.valueOf(config.get(HConstants.HBASE_CLIENT_IPC_POOL_TYPE),
293 PoolMap.PoolType.RoundRobin, PoolMap.PoolType.ThreadLocal);
294 }
295
296
297
298
299
300
301
302 private static int getPoolSize(Configuration config) {
303 return config.getInt(HConstants.HBASE_CLIENT_IPC_POOL_SIZE, 1);
304 }
305
306 private int nextCallId() {
307 int id, next;
308 do {
309 id = callIdCnt.get();
310 next = id < Integer.MAX_VALUE ? id + 1 : 0;
311 } while (!callIdCnt.compareAndSet(id, next));
312 return id;
313 }
314
315
316
317
318
319
320
321
322
323 private Message callBlockingMethod(Descriptors.MethodDescriptor md, HBaseRpcController hrc,
324 Message param, Message returnType, final User ticket, final InetSocketAddress isa)
325 throws ServiceException {
326 BlockingRpcCallback<Message> done = new BlockingRpcCallback<>();
327 callMethod(md, hrc, param, returnType, ticket, isa, done);
328 Message val;
329 try {
330 val = done.get();
331 } catch (IOException e) {
332 throw new ServiceException(e);
333 }
334 if (hrc.failed()) {
335 throw new ServiceException(hrc.getFailed());
336 } else {
337 return val;
338 }
339 }
340
341
342
343
344
345 private T getConnection(ConnectionId remoteId) throws IOException {
346 if (failedServers.isFailedServer(remoteId.getAddress())) {
347 if (LOG.isDebugEnabled()) {
348 LOG.debug("Not trying to connect to " + remoteId.address
349 + " this server is in the failed servers list");
350 }
351 throw new FailedServerException(
352 "This server is in the failed servers list: " + remoteId.address);
353 }
354 T conn;
355 synchronized (connections) {
356 if (!running) {
357 throw new StoppedRpcClientException();
358 }
359 conn = connections.get(remoteId);
360 if (conn == null) {
361 conn = createConnection(remoteId);
362 connections.put(remoteId, conn);
363 }
364 conn.setLastTouched(EnvironmentEdgeManager.currentTime());
365 }
366 return conn;
367 }
368
369
370
371
372 protected abstract T createConnection(ConnectionId remoteId) throws IOException;
373
374 private void onCallFinished(Call call, HBaseRpcController hrc, InetSocketAddress addr,
375 RpcCallback<Message> callback) {
376 call.callStats.setCallTimeMs(EnvironmentEdgeManager.currentTime() - call.getStartTime());
377 if (metrics != null) {
378 metrics.updateRpc(call.md, call.param, call.callStats);
379 }
380 if (LOG.isTraceEnabled()) {
381 LOG.trace(
382 "Call: " + call.md.getName() + ", callTime: " + call.callStats.getCallTimeMs() + "ms");
383 }
384 if (call.error != null) {
385 if (call.error instanceof RemoteException) {
386 call.error.fillInStackTrace();
387 hrc.setFailed(call.error);
388 } else {
389 hrc.setFailed(wrapException(addr, call.error));
390 }
391 callback.run(null);
392 } else {
393 hrc.setDone(call.cells);
394 callback.run(call.response);
395 }
396 }
397
398 private void callMethod(final Descriptors.MethodDescriptor md, final HBaseRpcController hrc,
399 final Message param, Message returnType, final User ticket, final InetSocketAddress addr,
400 final RpcCallback<Message> callback) {
401 final MetricsConnection.CallStats cs = MetricsConnection.newCallStats();
402 cs.setStartTime(EnvironmentEdgeManager.currentTime());
403 final AtomicInteger counter = concurrentCounterCache.getUnchecked(addr);
404 Call call = new Call(nextCallId(), md, param, hrc.cellScanner(), returnType,
405 hrc.getCallTimeout(), hrc.getPriority(), new RpcCallback<Call>() {
406 @Override
407 public void run(Call call) {
408 counter.decrementAndGet();
409 onCallFinished(call, hrc, addr, callback);
410 }
411 }, cs);
412 ConnectionId remoteId = new ConnectionId(ticket, md.getService().getName(), addr);
413 int count = counter.incrementAndGet();
414 try {
415 if (count > maxConcurrentCallsPerServer) {
416 throw new ServerTooBusyException(addr, count);
417 }
418 cs.setConcurrentCallsPerServer(count);
419 T connection = getConnection(remoteId);
420 connection.sendRequest(call, hrc);
421 } catch (Exception e) {
422 call.setException(toIOE(e));
423 }
424 }
425
426 private InetSocketAddress createAddr(ServerName sn) throws UnknownHostException {
427 InetSocketAddress addr = new InetSocketAddress(sn.getHostname(), sn.getPort());
428 if (addr.isUnresolved()) {
429 throw new UnknownHostException("can not resolve " + sn.getServerName());
430 }
431 return addr;
432 }
433
434
435
436
437
438
439
440
441 @Override
442 public void cancelConnections(ServerName sn) {
443 synchronized (connections) {
444 for (T connection : connections.values()) {
445 ConnectionId remoteId = connection.remoteId();
446 if (remoteId.address.getPort() == sn.getPort() &&
447 remoteId.address.getHostName().equals(sn.getHostname())) {
448 LOG.info("The server on " + sn.toString() + " is dead - stopping the connection " +
449 connection.remoteId);
450 connections.removeValue(remoteId, connection);
451 connection.shutdown();
452 }
453 }
454 }
455 }
456
457
458
459
460
461
462
463 static HBaseRpcController configureHBaseRpcController(
464 RpcController controller, int channelOperationTimeout) {
465 HBaseRpcController hrc;
466 if (controller != null && controller instanceof HBaseRpcController) {
467 hrc = (HBaseRpcController) controller;
468 if (!hrc.hasCallTimeout()) {
469 hrc.setCallTimeout(channelOperationTimeout);
470 }
471 } else {
472 hrc = new HBaseRpcControllerImpl();
473 hrc.setCallTimeout(channelOperationTimeout);
474 }
475 return hrc;
476 }
477
478 protected abstract void closeInternal();
479
480 @Override
481 public void close() {
482 if (LOG.isDebugEnabled()) {
483 LOG.debug("Stopping rpc client");
484 }
485 Collection<T> connToClose;
486 synchronized (connections) {
487 if (!running) {
488 return;
489 }
490 running = false;
491 connToClose = connections.values();
492 connections.clear();
493 }
494 cleanupIdleConnectionTask.cancel(true);
495 for (T conn : connToClose) {
496 conn.shutdown();
497 }
498 closeInternal();
499 for (T conn : connToClose) {
500 conn.cleanupConnection();
501 }
502 }
503
504 @Override
505 public BlockingRpcChannel createBlockingRpcChannel(final ServerName sn, final User ticket,
506 int rpcTimeout) throws UnknownHostException {
507 return new BlockingRpcChannelImplementation(this, createAddr(sn), ticket, rpcTimeout);
508 }
509
510 @Override
511 public RpcChannel createRpcChannel(ServerName sn, User user, int rpcTimeout)
512 throws UnknownHostException {
513 return new RpcChannelImplementation(this, createAddr(sn), user, rpcTimeout);
514 }
515
516 private static class AbstractRpcChannel {
517
518 protected final InetSocketAddress addr;
519
520 protected final AbstractRpcClient<?> rpcClient;
521
522 protected final User ticket;
523
524 protected final int rpcTimeout;
525
526 protected AbstractRpcChannel(AbstractRpcClient<?> rpcClient, InetSocketAddress addr,
527 User ticket, int rpcTimeout) {
528 this.addr = addr;
529 this.rpcClient = rpcClient;
530 this.ticket = ticket;
531 this.rpcTimeout = rpcTimeout;
532 }
533
534
535
536
537
538
539 protected HBaseRpcController configureRpcController(RpcController controller) {
540 HBaseRpcController hrc;
541
542
543 if (controller != null && controller instanceof HBaseRpcController) {
544 hrc = (HBaseRpcController) controller;
545 if (!hrc.hasCallTimeout()) {
546 hrc.setCallTimeout(rpcTimeout);
547 }
548 } else {
549 hrc = new HBaseRpcControllerImpl();
550 hrc.setCallTimeout(rpcTimeout);
551 }
552 return hrc;
553 }
554 }
555
556
557
558
559 @VisibleForTesting
560 public static class BlockingRpcChannelImplementation extends AbstractRpcChannel
561 implements BlockingRpcChannel {
562
563 protected BlockingRpcChannelImplementation(AbstractRpcClient<?> rpcClient,
564 InetSocketAddress addr, User ticket, int rpcTimeout) {
565 super(rpcClient, addr, ticket, rpcTimeout);
566 }
567
568 @Override
569 public Message callBlockingMethod(Descriptors.MethodDescriptor md, RpcController controller,
570 Message param, Message returnType) throws ServiceException {
571 return rpcClient.callBlockingMethod(md, configureRpcController(controller),
572 param, returnType, ticket, addr);
573 }
574 }
575
576
577
578
579 public static class RpcChannelImplementation extends AbstractRpcChannel implements
580 RpcChannel {
581
582 protected RpcChannelImplementation(AbstractRpcClient<?> rpcClient, InetSocketAddress addr,
583 User ticket, int rpcTimeout) throws UnknownHostException {
584 super(rpcClient, addr, ticket, rpcTimeout);
585 }
586
587 @Override
588 public void callMethod(Descriptors.MethodDescriptor md, RpcController controller,
589 Message param, Message returnType, RpcCallback<Message> done) {
590
591
592 this.rpcClient.callMethod(md,
593 configureRpcController(Preconditions.checkNotNull(controller,
594 "RpcController can not be null for async rpc call")),
595 param, returnType, ticket, addr, done);
596 }
597 }
598 }