1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.client;
20
21 import static org.apache.hadoop.hbase.client.MetricsConnection.CLIENT_SIDE_METRICS_ENABLED_KEY;
22
23 import java.io.Closeable;
24 import java.io.IOException;
25 import java.io.InterruptedIOException;
26 import java.lang.reflect.UndeclaredThrowableException;
27 import java.net.InetAddress;
28 import java.net.InetSocketAddress;
29 import java.util.ArrayList;
30 import java.util.Date;
31 import java.util.HashSet;
32 import java.util.LinkedHashMap;
33 import java.util.List;
34 import java.util.concurrent.BlockingQueue;
35 import java.util.Map;
36 import java.util.Map.Entry;
37 import java.util.NavigableMap;
38 import java.util.Set;
39 import java.util.concurrent.ConcurrentHashMap;
40 import java.util.concurrent.ConcurrentMap;
41 import java.util.concurrent.ExecutorService;
42 import java.util.concurrent.LinkedBlockingQueue;
43 import java.util.concurrent.ThreadPoolExecutor;
44 import java.util.concurrent.TimeUnit;
45 import java.util.concurrent.atomic.AtomicBoolean;
46 import java.util.concurrent.atomic.AtomicInteger;
47 import java.util.concurrent.locks.ReentrantLock;
48
49 import org.apache.commons.logging.Log;
50 import org.apache.commons.logging.LogFactory;
51 import org.apache.hadoop.conf.Configuration;
52 import org.apache.hadoop.hbase.CallQueueTooBigException;
53 import org.apache.hadoop.hbase.DoNotRetryIOException;
54 import org.apache.hadoop.hbase.HBaseConfiguration;
55 import org.apache.hadoop.hbase.HConstants;
56 import org.apache.hadoop.hbase.HRegionInfo;
57 import org.apache.hadoop.hbase.HRegionLocation;
58 import org.apache.hadoop.hbase.HTableDescriptor;
59 import org.apache.hadoop.hbase.MasterNotRunningException;
60 import org.apache.hadoop.hbase.MetaTableAccessor;
61 import org.apache.hadoop.hbase.RegionLocations;
62 import org.apache.hadoop.hbase.ServerName;
63 import org.apache.hadoop.hbase.TableName;
64 import org.apache.hadoop.hbase.TableNotEnabledException;
65 import org.apache.hadoop.hbase.TableNotFoundException;
66 import org.apache.hadoop.hbase.ZooKeeperConnectionException;
67 import org.apache.hadoop.hbase.classification.InterfaceAudience;
68 import org.apache.hadoop.hbase.client.AsyncProcess.AsyncRequestFuture;
69 import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitor;
70 import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitorBase;
71 import org.apache.hadoop.hbase.client.backoff.ClientBackoffPolicy;
72 import org.apache.hadoop.hbase.client.backoff.ClientBackoffPolicyFactory;
73 import org.apache.hadoop.hbase.client.coprocessor.Batch;
74 import org.apache.hadoop.hbase.exceptions.ClientExceptionsUtil;
75 import org.apache.hadoop.hbase.exceptions.RegionMovedException;
76 import org.apache.hadoop.hbase.ipc.RpcClient;
77 import org.apache.hadoop.hbase.ipc.RpcClientFactory;
78 import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
79 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
80 import org.apache.hadoop.hbase.protobuf.RequestConverter;
81 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
82 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ClientService;
83 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceRequest;
84 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceResponse;
85 import org.apache.hadoop.hbase.protobuf.generated.*;
86 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.AddColumnRequest;
87 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.AddColumnResponse;
88 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.AssignRegionRequest;
89 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.AssignRegionResponse;
90 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.BalanceRequest;
91 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.BalanceResponse;
92 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateNamespaceRequest;
93 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateNamespaceResponse;
94 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateTableRequest;
95 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateTableResponse;
96 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteColumnRequest;
97 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteColumnResponse;
98 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteNamespaceRequest;
99 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteNamespaceResponse;
100 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteSnapshotRequest;
101 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteSnapshotResponse;
102 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteTableRequest;
103 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteTableResponse;
104 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DisableTableRequest;
105 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DisableTableResponse;
106 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DispatchMergingRegionsRequest;
107 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DispatchMergingRegionsResponse;
108 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.EnableCatalogJanitorRequest;
109 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.EnableCatalogJanitorResponse;
110 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.EnableTableRequest;
111 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.EnableTableResponse;
112 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ExecProcedureRequest;
113 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ExecProcedureResponse;
114 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetClusterStatusRequest;
115 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetClusterStatusResponse;
116 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetCompletedSnapshotsRequest;
117 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetCompletedSnapshotsResponse;
118 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetNamespaceDescriptorRequest;
119 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetNamespaceDescriptorResponse;
120 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetSchemaAlterStatusRequest;
121 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetSchemaAlterStatusResponse;
122 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableDescriptorsRequest;
123 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableDescriptorsResponse;
124 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableNamesRequest;
125 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableNamesResponse;
126 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetProcedureResultRequest;
127 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetProcedureResultResponse;
128 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsBalancerEnabledRequest;
129 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsBalancerEnabledResponse;
130 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsCatalogJanitorEnabledRequest;
131 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsCatalogJanitorEnabledResponse;
132 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsCleanerChoreEnabledRequest;
133 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsCleanerChoreEnabledResponse;
134 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsMasterRunningRequest;
135 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsMasterRunningResponse;
136 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsNormalizerEnabledRequest;
137 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsNormalizerEnabledResponse;
138 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsProcedureDoneRequest;
139 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsProcedureDoneResponse;
140 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsRestoreSnapshotDoneRequest;
141 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsRestoreSnapshotDoneResponse;
142 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneRequest;
143 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneResponse;
144 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListNamespaceDescriptorsRequest;
145 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListNamespaceDescriptorsResponse;
146 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListTableDescriptorsByNamespaceRequest;
147 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListTableDescriptorsByNamespaceResponse;
148 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListTableNamesByNamespaceRequest;
149 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListTableNamesByNamespaceResponse;
150 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MajorCompactionTimestampForRegionRequest;
151 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MajorCompactionTimestampRequest;
152 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MajorCompactionTimestampResponse;
153 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MasterService;
154 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyColumnRequest;
155 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyColumnResponse;
156 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyNamespaceRequest;
157 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyNamespaceResponse;
158 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyTableRequest;
159 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyTableResponse;
160 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MoveRegionRequest;
161 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MoveRegionResponse;
162 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.NormalizeRequest;
163 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.NormalizeResponse;
164 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.OfflineRegionRequest;
165 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.OfflineRegionResponse;
166 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RestoreSnapshotRequest;
167 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RestoreSnapshotResponse;
168 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RunCatalogScanRequest;
169 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RunCatalogScanResponse;
170 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RunCleanerChoreRequest;
171 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RunCleanerChoreResponse;
172 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SecurityCapabilitiesRequest;
173 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SecurityCapabilitiesResponse;
174 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SetBalancerRunningRequest;
175 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SetBalancerRunningResponse;
176 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SetCleanerChoreRunningRequest;
177 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SetCleanerChoreRunningResponse;
178 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SetNormalizerRunningRequest;
179 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SetNormalizerRunningResponse;
180 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SetQuotaRequest;
181 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SetQuotaResponse;
182 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ShutdownRequest;
183 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ShutdownResponse;
184 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SnapshotRequest;
185 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SnapshotResponse;
186 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.StopMasterRequest;
187 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.StopMasterResponse;
188 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.TruncateTableRequest;
189 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.TruncateTableResponse;
190 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.UnassignRegionRequest;
191 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.UnassignRegionResponse;
192 import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
193 import org.apache.hadoop.hbase.security.User;
194 import org.apache.hadoop.hbase.security.UserProvider;
195 import org.apache.hadoop.hbase.util.Bytes;
196 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
197 import org.apache.hadoop.hbase.util.ExceptionUtil;
198 import org.apache.hadoop.hbase.util.Threads;
199 import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker;
200 import org.apache.hadoop.hbase.zookeeper.ZKUtil;
201 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
202 import org.apache.hadoop.ipc.RemoteException;
203 import org.apache.zookeeper.KeeperException;
204
205 import com.google.common.annotations.VisibleForTesting;
206 import com.google.protobuf.BlockingRpcChannel;
207 import com.google.protobuf.RpcController;
208 import com.google.protobuf.ServiceException;
209
210
211
212
213 @SuppressWarnings("serial")
214 @InterfaceAudience.Private
215
216 class ConnectionManager {
217 static final Log LOG = LogFactory.getLog(ConnectionManager.class);
218
219 public static final String RETRIES_BY_SERVER_KEY = "hbase.client.retries.by.server";
220 private static final String CLIENT_NONCES_ENABLED_KEY = "hbase.client.nonces.enabled";
221 private static final String RESOLVE_HOSTNAME_ON_FAIL_KEY = "hbase.resolve.hostnames.on.failure";
222
223
224
225
226 static final Map<HConnectionKey, HConnectionImplementation> CONNECTION_INSTANCES;
227
228 public static final int MAX_CACHED_CONNECTION_INSTANCES;
229
230
231
232
233
234 private static volatile NonceGenerator nonceGenerator = null;
235
236 private static Object nonceGeneratorCreateLock = new Object();
237
238 static {
239
240
241
242
243 MAX_CACHED_CONNECTION_INSTANCES = HBaseConfiguration.create().getInt(
244 HConstants.ZOOKEEPER_MAX_CLIENT_CNXNS, HConstants.DEFAULT_ZOOKEPER_MAX_CLIENT_CNXNS) + 1;
245 CONNECTION_INSTANCES = new LinkedHashMap<HConnectionKey, HConnectionImplementation>(
246 (int) (MAX_CACHED_CONNECTION_INSTANCES / 0.75F) + 1, 0.75F, true) {
247 @Override
248 protected boolean removeEldestEntry(
249 Map.Entry<HConnectionKey, HConnectionImplementation> eldest) {
250 return size() > MAX_CACHED_CONNECTION_INSTANCES;
251 }
252 };
253 }
254
255
256 static class NoNonceGenerator implements NonceGenerator {
257 @Override
258 public long getNonceGroup() {
259 return HConstants.NO_NONCE;
260 }
261 @Override
262 public long newNonce() {
263 return HConstants.NO_NONCE;
264 }
265 }
266
267
268
269
270 private ConnectionManager() {
271 super();
272 }
273
274
275
276
277
278
279 @VisibleForTesting
280 static NonceGenerator injectNonceGeneratorForTesting(
281 ClusterConnection conn, NonceGenerator cnm) {
282 HConnectionImplementation connImpl = (HConnectionImplementation)conn;
283 NonceGenerator ng = connImpl.getNonceGenerator();
284 LOG.warn("Nonce generator is being replaced by test code for " + cnm.getClass().getName());
285 connImpl.nonceGenerator = cnm;
286 return ng;
287 }
288
289
290
291
292
293
294
295
296
297
298 @Deprecated
299 public static HConnection getConnection(final Configuration conf) throws IOException {
300 return getConnectionInternal(conf);
301 }
302
303
304 static ClusterConnection getConnectionInternal(final Configuration conf)
305 throws IOException {
306 HConnectionKey connectionKey = new HConnectionKey(conf);
307 synchronized (CONNECTION_INSTANCES) {
308 HConnectionImplementation connection = CONNECTION_INSTANCES.get(connectionKey);
309 if (connection == null) {
310 connection = (HConnectionImplementation)createConnection(conf, true);
311 CONNECTION_INSTANCES.put(connectionKey, connection);
312 } else if (connection.isClosed()) {
313 ConnectionManager.deleteConnection(connectionKey, true);
314 connection = (HConnectionImplementation)createConnection(conf, true);
315 CONNECTION_INSTANCES.put(connectionKey, connection);
316 }
317 connection.incCount();
318 return connection;
319 }
320 }
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342 public static HConnection createConnection(Configuration conf) throws IOException {
343 return createConnectionInternal(conf);
344 }
345
346 static ClusterConnection createConnectionInternal(Configuration conf) throws IOException {
347 UserProvider provider = UserProvider.instantiate(conf);
348 return createConnection(conf, false, null, provider.getCurrent());
349 }
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371 public static HConnection createConnection(Configuration conf, ExecutorService pool)
372 throws IOException {
373 UserProvider provider = UserProvider.instantiate(conf);
374 return createConnection(conf, false, pool, provider.getCurrent());
375 }
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397 public static HConnection createConnection(Configuration conf, User user)
398 throws IOException {
399 return createConnection(conf, false, null, user);
400 }
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423 public static HConnection createConnection(Configuration conf, ExecutorService pool, User user)
424 throws IOException {
425 return createConnection(conf, false, pool, user);
426 }
427
428 @Deprecated
429 static HConnection createConnection(final Configuration conf, final boolean managed)
430 throws IOException {
431 UserProvider provider = UserProvider.instantiate(conf);
432 return createConnection(conf, managed, null, provider.getCurrent());
433 }
434
435 @Deprecated
436 static ClusterConnection createConnection(final Configuration conf, final boolean managed,
437 final ExecutorService pool, final User user)
438 throws IOException {
439 return (ClusterConnection) ConnectionFactory.createConnection(conf, managed, pool, user);
440 }
441
442
443
444
445
446
447
448
449
450 @Deprecated
451 public static void deleteConnection(Configuration conf) {
452 deleteConnection(new HConnectionKey(conf), false);
453 }
454
455
456
457
458
459
460
461
462 @Deprecated
463 public static void deleteStaleConnection(HConnection connection) {
464 deleteConnection(connection, true);
465 }
466
467
468
469
470
471
472
473 @Deprecated
474 public static void deleteAllConnections(boolean staleConnection) {
475 synchronized (CONNECTION_INSTANCES) {
476 Set<HConnectionKey> connectionKeys = new HashSet<HConnectionKey>();
477 connectionKeys.addAll(CONNECTION_INSTANCES.keySet());
478 for (HConnectionKey connectionKey : connectionKeys) {
479 deleteConnection(connectionKey, staleConnection);
480 }
481 CONNECTION_INSTANCES.clear();
482 }
483 }
484
485
486
487
488
489 @Deprecated
490 public static void deleteAllConnections() {
491 deleteAllConnections(false);
492 }
493
494
495 @Deprecated
496 private static void deleteConnection(HConnection connection, boolean staleConnection) {
497 synchronized (CONNECTION_INSTANCES) {
498 for (Entry<HConnectionKey, HConnectionImplementation> e: CONNECTION_INSTANCES.entrySet()) {
499 if (e.getValue() == connection) {
500 deleteConnection(e.getKey(), staleConnection);
501 break;
502 }
503 }
504 }
505 }
506
507 @Deprecated
508 private static void deleteConnection(HConnectionKey connectionKey, boolean staleConnection) {
509 synchronized (CONNECTION_INSTANCES) {
510 HConnectionImplementation connection = CONNECTION_INSTANCES.get(connectionKey);
511 if (connection != null) {
512 connection.decCount();
513 if (connection.isZeroReference() || staleConnection) {
514 CONNECTION_INSTANCES.remove(connectionKey);
515 connection.internalClose();
516 }
517 } else {
518 LOG.error("Connection not found in the list, can't delete it "+
519 "(connection key=" + connectionKey + "). May be the key was modified?", new Exception());
520 }
521 }
522 }
523
524
525
526
527
528
529
530
531
532
533
534
535 @InterfaceAudience.Private
536 public static <T> T execute(HConnectable<T> connectable) throws IOException {
537 if (connectable == null || connectable.conf == null) {
538 return null;
539 }
540 Configuration conf = connectable.conf;
541 HConnection connection = getConnection(conf);
542 boolean connectSucceeded = false;
543 try {
544 T returnValue = connectable.connect(connection);
545 connectSucceeded = true;
546 return returnValue;
547 } finally {
548 try {
549 connection.close();
550 } catch (Exception e) {
551 ExceptionUtil.rethrowIfInterrupt(e);
552 if (connectSucceeded) {
553 throw new IOException("The connection to " + connection
554 + " could not be deleted.", e);
555 }
556 }
557 }
558 }
559
560
561 @edu.umd.cs.findbugs.annotations.SuppressWarnings(
562 value="AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION",
563 justification="Access to the conncurrent hash map is under a lock so should be fine.")
564 static class HConnectionImplementation implements ClusterConnection, Closeable {
565 static final Log LOG = LogFactory.getLog(HConnectionImplementation.class);
566 private final boolean hostnamesCanChange;
567 private final long pause;
568 private final long pauseForCQTBE;
569 private boolean useMetaReplicas;
570 private final int metaReplicaCallTimeoutScanInMicroSecond;
571 private final int numTries;
572 final int rpcTimeout;
573 final int writeRpcTimeout;
574 private NonceGenerator nonceGenerator = null;
575 private final AsyncProcess asyncProcess;
576
577 private final ServerStatisticTracker stats;
578
579 private volatile boolean closed;
580 private volatile boolean aborted;
581
582
583 ClusterStatusListener clusterStatusListener;
584
585
586 private final Object metaRegionLock = new Object();
587
588
589
590
591
592
593 private final Object masterAndZKLock = new Object();
594
595 private long keepZooKeeperWatcherAliveUntil = Long.MAX_VALUE;
596
597
598
599 private volatile ExecutorService batchPool = null;
600
601
602 private volatile ExecutorService metaLookupPool = null;
603 private volatile boolean cleanupPool = false;
604
605 private final Configuration conf;
606
607
608
609 private final ConnectionConfiguration connectionConfig;
610
611
612 private RpcClient rpcClient;
613
614 private final MetaCache metaCache;
615 private final MetricsConnection metrics;
616
617 private int refCount;
618
619
620 private boolean managed;
621
622 protected User user;
623
624 private RpcRetryingCallerFactory rpcCallerFactory;
625
626 private RpcControllerFactory rpcControllerFactory;
627
628 private final RetryingCallerInterceptor interceptor;
629
630
631
632
633 Registry registry;
634
635 private final ClientBackoffPolicy backoffPolicy;
636
637
638 private final ReentrantLock userRegionLock = new ReentrantLock();
639
640
641 HConnectionImplementation(Configuration conf, boolean managed) throws IOException {
642 this(conf, managed, null, null);
643 }
644
645
646
647
648
649
650
651
652
653
654
655
656 HConnectionImplementation(Configuration conf, boolean managed,
657 ExecutorService pool, User user) throws IOException {
658 this.conf = conf;
659 this.user = user;
660 this.batchPool = pool;
661 this.managed = managed;
662 this.connectionConfig = new ConnectionConfiguration(conf);
663 this.closed = false;
664 this.pause = conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
665 HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
666 long configuredPauseForCQTBE = conf.getLong(HConstants.HBASE_CLIENT_PAUSE_FOR_CQTBE, pause);
667 if (configuredPauseForCQTBE < pause) {
668 LOG.warn("The " + HConstants.HBASE_CLIENT_PAUSE_FOR_CQTBE + " setting: "
669 + configuredPauseForCQTBE + " is smaller than " + HConstants.HBASE_CLIENT_PAUSE
670 + ", will use " + pause + " instead.");
671 this.pauseForCQTBE = pause;
672 } else {
673 this.pauseForCQTBE = configuredPauseForCQTBE;
674 }
675 this.useMetaReplicas = conf.getBoolean(HConstants.USE_META_REPLICAS,
676 HConstants.DEFAULT_USE_META_REPLICAS);
677 this.metaReplicaCallTimeoutScanInMicroSecond =
678 connectionConfig.getMetaReplicaCallTimeoutMicroSecondScan();
679
680 this.numTries = connectionConfig.getRetriesNumber();
681 this.rpcTimeout = conf.getInt(
682 HConstants.HBASE_RPC_TIMEOUT_KEY,
683 HConstants.DEFAULT_HBASE_RPC_TIMEOUT);
684 this.writeRpcTimeout = conf.getInt(
685 HConstants.HBASE_RPC_WRITE_TIMEOUT_KEY,
686 HConstants.DEFAULT_HBASE_RPC_TIMEOUT);
687 if (conf.getBoolean(CLIENT_NONCES_ENABLED_KEY, true)) {
688 synchronized (nonceGeneratorCreateLock) {
689 if (ConnectionManager.nonceGenerator == null) {
690 ConnectionManager.nonceGenerator = new PerClientRandomNonceGenerator();
691 }
692 this.nonceGenerator = ConnectionManager.nonceGenerator;
693 }
694 } else {
695 this.nonceGenerator = new NoNonceGenerator();
696 }
697
698 this.stats = ServerStatisticTracker.create(conf);
699 this.interceptor = (new RetryingCallerInterceptorFactory(conf)).build();
700 this.rpcControllerFactory = RpcControllerFactory.instantiate(conf);
701 this.rpcCallerFactory = RpcRetryingCallerFactory.instantiate(conf, interceptor, this.stats);
702 this.backoffPolicy = ClientBackoffPolicyFactory.create(conf);
703 this.asyncProcess = createAsyncProcess(this.conf);
704 if (conf.getBoolean(CLIENT_SIDE_METRICS_ENABLED_KEY, false)) {
705 this.metrics = new MetricsConnection(this);
706 } else {
707 this.metrics = null;
708 }
709 this.metaCache = new MetaCache(this.metrics);
710
711 this.hostnamesCanChange = conf.getBoolean(RESOLVE_HOSTNAME_ON_FAIL_KEY, true);
712 boolean shouldListen = conf.getBoolean(HConstants.STATUS_PUBLISHED,
713 HConstants.STATUS_PUBLISHED_DEFAULT);
714 Class<? extends ClusterStatusListener.Listener> listenerClass =
715 conf.getClass(ClusterStatusListener.STATUS_LISTENER_CLASS,
716 ClusterStatusListener.DEFAULT_STATUS_LISTENER_CLASS,
717 ClusterStatusListener.Listener.class);
718
719 try {
720 this.registry = setupRegistry();
721 retrieveClusterId();
722
723 this.rpcClient = RpcClientFactory.createClient(this.conf, this.clusterId, this.metrics);
724
725
726 if (shouldListen) {
727 if (listenerClass == null) {
728 LOG.warn(HConstants.STATUS_PUBLISHED + " is true, but " +
729 ClusterStatusListener.STATUS_LISTENER_CLASS + " is not set - not listening status");
730 } else {
731 clusterStatusListener = new ClusterStatusListener(
732 new ClusterStatusListener.DeadServerHandler() {
733 @Override
734 public void newDead(ServerName sn) {
735 clearCaches(sn);
736 rpcClient.cancelConnections(sn);
737 }
738 }, conf, listenerClass);
739 }
740 }
741 } catch (Throwable e) {
742
743 LOG.debug("connection construction failed", e);
744 close();
745 throw e;
746 }
747 }
748
749
750
751
752 @VisibleForTesting
753 void setUseMetaReplicas(final boolean useMetaReplicas) {
754 this.useMetaReplicas = useMetaReplicas;
755 }
756
757 @Override
758 public HTableInterface getTable(String tableName) throws IOException {
759 return getTable(TableName.valueOf(tableName));
760 }
761
762 @Override
763 public HTableInterface getTable(byte[] tableName) throws IOException {
764 return getTable(TableName.valueOf(tableName));
765 }
766
767 @Override
768 public HTableInterface getTable(TableName tableName) throws IOException {
769 return getTable(tableName, getBatchPool());
770 }
771
772 @Override
773 public HTableInterface getTable(String tableName, ExecutorService pool) throws IOException {
774 return getTable(TableName.valueOf(tableName), pool);
775 }
776
777 @Override
778 public HTableInterface getTable(byte[] tableName, ExecutorService pool) throws IOException {
779 return getTable(TableName.valueOf(tableName), pool);
780 }
781
782 @Override
783 public HTableInterface getTable(TableName tableName, ExecutorService pool) throws IOException {
784 if (managed) {
785 throw new NeedUnmanagedConnectionException();
786 }
787 return new HTable(tableName, this, connectionConfig, rpcCallerFactory, rpcControllerFactory, pool);
788 }
789
790 @Override
791 public BufferedMutator getBufferedMutator(BufferedMutatorParams params) {
792 if (params.getTableName() == null) {
793 throw new IllegalArgumentException("TableName cannot be null.");
794 }
795 if (params.getPool() == null) {
796 params.pool(HTable.getDefaultExecutor(getConfiguration()));
797 }
798 if (params.getWriteBufferSize() == BufferedMutatorParams.UNSET) {
799 params.writeBufferSize(connectionConfig.getWriteBufferSize());
800 }
801 if (params.getMaxKeyValueSize() == BufferedMutatorParams.UNSET) {
802 params.maxKeyValueSize(connectionConfig.getMaxKeyValueSize());
803 }
804 return new BufferedMutatorImpl(this, rpcCallerFactory, rpcControllerFactory, params);
805 }
806
807 @Override
808 public BufferedMutator getBufferedMutator(TableName tableName) {
809 return getBufferedMutator(new BufferedMutatorParams(tableName));
810 }
811
812 @Override
813 public RegionLocator getRegionLocator(TableName tableName) throws IOException {
814 return new HRegionLocator(tableName, this);
815 }
816
817 @Override
818 public Admin getAdmin() throws IOException {
819 if (managed) {
820 throw new NeedUnmanagedConnectionException();
821 }
822 return new HBaseAdmin(this);
823 }
824
825 @Override
826 public MetricsConnection getConnectionMetrics() {
827 return this.metrics;
828 }
829
830 private ExecutorService getBatchPool() {
831 if (batchPool == null) {
832 synchronized (this) {
833 if (batchPool == null) {
834 this.batchPool = getThreadPool(conf.getInt("hbase.hconnection.threads.max", 256),
835 conf.getInt("hbase.hconnection.threads.core", 256), "-shared-", null);
836 this.cleanupPool = true;
837 }
838 }
839 }
840 return this.batchPool;
841 }
842
843 private ExecutorService getThreadPool(int maxThreads, int coreThreads, String nameHint,
844 BlockingQueue<Runnable> passedWorkQueue) {
845
846 if (maxThreads == 0) {
847 maxThreads = Runtime.getRuntime().availableProcessors() * 8;
848 }
849 if (coreThreads == 0) {
850 coreThreads = Runtime.getRuntime().availableProcessors() * 8;
851 }
852 long keepAliveTime = conf.getLong("hbase.hconnection.threads.keepalivetime", 60);
853 BlockingQueue<Runnable> workQueue = passedWorkQueue;
854 if (workQueue == null) {
855 workQueue =
856 new LinkedBlockingQueue<Runnable>(maxThreads *
857 conf.getInt(HConstants.HBASE_CLIENT_MAX_TOTAL_TASKS,
858 HConstants.DEFAULT_HBASE_CLIENT_MAX_TOTAL_TASKS));
859 }
860 ThreadPoolExecutor tpe = new ThreadPoolExecutor(
861 coreThreads,
862 maxThreads,
863 keepAliveTime,
864 TimeUnit.SECONDS,
865 workQueue,
866 Threads.newDaemonThreadFactory(toString() + nameHint));
867 tpe.allowCoreThreadTimeOut(true);
868 return tpe;
869 }
870
871 private ExecutorService getMetaLookupPool() {
872 if (this.metaLookupPool == null) {
873 synchronized (this) {
874 if (this.metaLookupPool == null) {
875
876
877
878
879 this.metaLookupPool = getThreadPool(
880 conf.getInt("hbase.hconnection.meta.lookup.threads.max", 128),
881 conf.getInt("hbase.hconnection.meta.lookup.threads.core", 10),
882 "-metaLookup-shared-", new LinkedBlockingQueue<Runnable>());
883 }
884 }
885 }
886 return this.metaLookupPool;
887 }
888
889 protected ExecutorService getCurrentMetaLookupPool() {
890 return metaLookupPool;
891 }
892
893 protected ExecutorService getCurrentBatchPool() {
894 return batchPool;
895 }
896
897 private void shutdownPools() {
898 if (this.cleanupPool && this.batchPool != null && !this.batchPool.isShutdown()) {
899 shutdownBatchPool(this.batchPool);
900 }
901 if (this.metaLookupPool != null && !this.metaLookupPool.isShutdown()) {
902 shutdownBatchPool(this.metaLookupPool);
903 }
904 }
905
906 private void shutdownBatchPool(ExecutorService pool) {
907 pool.shutdown();
908 try {
909 if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
910 pool.shutdownNow();
911 }
912 } catch (InterruptedException e) {
913 pool.shutdownNow();
914 }
915 }
916
917
918
919
920
921 private Registry setupRegistry() throws IOException {
922 return RegistryFactory.getRegistry(this);
923 }
924
925
926
927
928 @VisibleForTesting
929 RpcClient getRpcClient() {
930 return rpcClient;
931 }
932
933
934
935
936 @Override
937 public String toString(){
938 return "hconnection-0x" + Integer.toHexString(hashCode());
939 }
940
941 protected String clusterId = null;
942
943 void retrieveClusterId() {
944 if (clusterId != null) return;
945 this.clusterId = this.registry.getClusterId();
946 if (clusterId == null) {
947 clusterId = HConstants.CLUSTER_ID_DEFAULT;
948 LOG.debug("clusterid came back null, using default " + clusterId);
949 }
950 }
951
952 @Override
953 public Configuration getConfiguration() {
954 return this.conf;
955 }
956
957 private void checkIfBaseNodeAvailable(ZooKeeperWatcher zkw)
958 throws MasterNotRunningException {
959 String errorMsg;
960 try {
961 if (ZKUtil.checkExists(zkw, zkw.baseZNode) == -1) {
962 errorMsg = "The node " + zkw.baseZNode+" is not in ZooKeeper. "
963 + "It should have been written by the master. "
964 + "Check the value configured in 'zookeeper.znode.parent'. "
965 + "There could be a mismatch with the one configured in the master.";
966 LOG.error(errorMsg);
967 throw new MasterNotRunningException(errorMsg);
968 }
969 } catch (KeeperException e) {
970 errorMsg = "Can't get connection to ZooKeeper: " + e.getMessage();
971 LOG.error(errorMsg);
972 throw new MasterNotRunningException(errorMsg, e);
973 }
974 }
975
976
977
978
979
980
981 @Deprecated
982 @Override
983 public boolean isMasterRunning()
984 throws MasterNotRunningException, ZooKeeperConnectionException {
985
986
987
988 MasterKeepAliveConnection m = getKeepAliveMasterService();
989 m.close();
990 return true;
991 }
992
993 @Override
994 public HRegionLocation getRegionLocation(final TableName tableName,
995 final byte [] row, boolean reload)
996 throws IOException {
997 return reload? relocateRegion(tableName, row): locateRegion(tableName, row);
998 }
999
1000 @Override
1001 public HRegionLocation getRegionLocation(final byte[] tableName,
1002 final byte [] row, boolean reload)
1003 throws IOException {
1004 return getRegionLocation(TableName.valueOf(tableName), row, reload);
1005 }
1006
1007 @Override
1008 public boolean isTableEnabled(TableName tableName) throws IOException {
1009 return this.registry.isTableOnlineState(tableName, true);
1010 }
1011
1012 @Override
1013 public boolean isTableEnabled(byte[] tableName) throws IOException {
1014 return isTableEnabled(TableName.valueOf(tableName));
1015 }
1016
1017 @Override
1018 public boolean isTableDisabled(TableName tableName) throws IOException {
1019 return this.registry.isTableOnlineState(tableName, false);
1020 }
1021
1022 @Override
1023 public boolean isTableDisabled(byte[] tableName) throws IOException {
1024 return isTableDisabled(TableName.valueOf(tableName));
1025 }
1026
1027 @Override
1028 public boolean isTableAvailable(final TableName tableName) throws IOException {
1029 final AtomicBoolean available = new AtomicBoolean(true);
1030 final AtomicInteger regionCount = new AtomicInteger(0);
1031 MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
1032 @Override
1033 public boolean processRow(Result row) throws IOException {
1034 HRegionInfo info = MetaScanner.getHRegionInfo(row);
1035 if (info != null && !info.isSplitParent()) {
1036 if (tableName.equals(info.getTable())) {
1037 ServerName server = HRegionInfo.getServerName(row);
1038 if (server == null) {
1039 available.set(false);
1040 return false;
1041 }
1042 regionCount.incrementAndGet();
1043 } else if (tableName.compareTo(info.getTable()) < 0) {
1044
1045 return false;
1046 }
1047 }
1048 return true;
1049 }
1050 };
1051 MetaScanner.metaScan(this, visitor, tableName);
1052 return available.get() && (regionCount.get() > 0);
1053 }
1054
1055 @Override
1056 public boolean isTableAvailable(final byte[] tableName) throws IOException {
1057 return isTableAvailable(TableName.valueOf(tableName));
1058 }
1059
1060 @Override
1061 public boolean isTableAvailable(final TableName tableName, final byte[][] splitKeys)
1062 throws IOException {
1063 final AtomicBoolean available = new AtomicBoolean(true);
1064 final AtomicInteger regionCount = new AtomicInteger(0);
1065 MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
1066 @Override
1067 public boolean processRow(Result row) throws IOException {
1068 HRegionInfo info = MetaScanner.getHRegionInfo(row);
1069 if (info != null && !info.isSplitParent()) {
1070 if (tableName.equals(info.getTable())) {
1071 ServerName server = HRegionInfo.getServerName(row);
1072 if (server == null) {
1073 available.set(false);
1074 return false;
1075 }
1076 if (!Bytes.equals(info.getStartKey(), HConstants.EMPTY_BYTE_ARRAY)) {
1077 for (byte[] splitKey : splitKeys) {
1078
1079 if (Bytes.equals(info.getStartKey(), splitKey)) {
1080 regionCount.incrementAndGet();
1081 break;
1082 }
1083 }
1084 } else {
1085
1086 regionCount.incrementAndGet();
1087 }
1088 } else if (tableName.compareTo(info.getTable()) < 0) {
1089
1090 return false;
1091 }
1092 }
1093 return true;
1094 }
1095 };
1096 MetaScanner.metaScan(this, visitor, tableName);
1097
1098 return available.get() && (regionCount.get() == splitKeys.length + 1);
1099 }
1100
1101 @Override
1102 public boolean isTableAvailable(final byte[] tableName, final byte[][] splitKeys)
1103 throws IOException {
1104 return isTableAvailable(TableName.valueOf(tableName), splitKeys);
1105 }
1106
1107 @Override
1108 public HRegionLocation locateRegion(final byte[] regionName) throws IOException {
1109 RegionLocations locations = locateRegion(HRegionInfo.getTable(regionName),
1110 HRegionInfo.getStartKey(regionName), false, true);
1111 return locations == null ? null : locations.getRegionLocation();
1112 }
1113
1114 @Override
1115 public boolean isDeadServer(ServerName sn) {
1116 if (clusterStatusListener == null) {
1117 return false;
1118 } else {
1119 return clusterStatusListener.isDeadServer(sn);
1120 }
1121 }
1122
1123 @Override
1124 public List<HRegionLocation> locateRegions(final TableName tableName)
1125 throws IOException {
1126 return locateRegions (tableName, false, true);
1127 }
1128
1129 @Override
1130 public List<HRegionLocation> locateRegions(final byte[] tableName)
1131 throws IOException {
1132 return locateRegions(TableName.valueOf(tableName));
1133 }
1134
1135 @Override
1136 public List<HRegionLocation> locateRegions(final TableName tableName,
1137 final boolean useCache, final boolean offlined) throws IOException {
1138 NavigableMap<HRegionInfo, ServerName> regions = MetaScanner.allTableRegions(this, tableName);
1139 final List<HRegionLocation> locations = new ArrayList<HRegionLocation>();
1140 for (HRegionInfo regionInfo : regions.keySet()) {
1141 if (!RegionReplicaUtil.isDefaultReplica(regionInfo)) {
1142 continue;
1143 }
1144 RegionLocations list = locateRegion(tableName, regionInfo.getStartKey(), useCache, true);
1145 if (list != null) {
1146 for (HRegionLocation loc : list.getRegionLocations()) {
1147 if (loc != null) {
1148 locations.add(loc);
1149 }
1150 }
1151 }
1152 }
1153 return locations;
1154 }
1155
1156 @Override
1157 public List<HRegionLocation> locateRegions(final byte[] tableName,
1158 final boolean useCache, final boolean offlined) throws IOException {
1159 return locateRegions(TableName.valueOf(tableName), useCache, offlined);
1160 }
1161
1162 @Override
1163 public HRegionLocation locateRegion(
1164 final TableName tableName, final byte[] row) throws IOException{
1165 RegionLocations locations = locateRegion(tableName, row, true, true);
1166 return locations == null ? null : locations.getRegionLocation();
1167 }
1168
1169 @Override
1170 public HRegionLocation locateRegion(final byte[] tableName,
1171 final byte [] row)
1172 throws IOException{
1173 return locateRegion(TableName.valueOf(tableName), row);
1174 }
1175
1176 @Override
1177 public HRegionLocation relocateRegion(final TableName tableName,
1178 final byte [] row) throws IOException{
1179 RegionLocations locations = relocateRegion(tableName, row,
1180 RegionReplicaUtil.DEFAULT_REPLICA_ID);
1181 return locations == null ? null :
1182 locations.getRegionLocation(RegionReplicaUtil.DEFAULT_REPLICA_ID);
1183 }
1184
1185 @Override
1186 public RegionLocations relocateRegion(final TableName tableName,
1187 final byte [] row, int replicaId) throws IOException{
1188
1189
1190
1191 if (!tableName.equals(TableName.META_TABLE_NAME) && isTableDisabled(tableName)) {
1192 throw new TableNotEnabledException(tableName.getNameAsString() + " is disabled.");
1193 }
1194
1195 return locateRegion(tableName, row, false, true, replicaId);
1196 }
1197
1198 @Override
1199 public HRegionLocation relocateRegion(final byte[] tableName,
1200 final byte [] row) throws IOException {
1201 return relocateRegion(TableName.valueOf(tableName), row);
1202 }
1203
1204 @Override
1205 public RegionLocations locateRegion(final TableName tableName,
1206 final byte [] row, boolean useCache, boolean retry)
1207 throws IOException {
1208 return locateRegion(tableName, row, useCache, retry, RegionReplicaUtil.DEFAULT_REPLICA_ID);
1209 }
1210
1211 @Override
1212 public RegionLocations locateRegion(final TableName tableName,
1213 final byte [] row, boolean useCache, boolean retry, int replicaId)
1214 throws IOException {
1215 if (this.closed) throw new DoNotRetryIOException(toString() + " closed");
1216 if (tableName== null || tableName.getName().length == 0) {
1217 throw new IllegalArgumentException(
1218 "table name cannot be null or zero length");
1219 }
1220 if (tableName.equals(TableName.META_TABLE_NAME)) {
1221 return locateMeta(tableName, useCache, replicaId);
1222 } else {
1223
1224 return locateRegionInMeta(tableName, row, useCache, retry, replicaId);
1225 }
1226 }
1227
1228 private RegionLocations locateMeta(final TableName tableName,
1229 boolean useCache, int replicaId) throws IOException {
1230
1231
1232
1233 byte[] metaCacheKey = HConstants.EMPTY_START_ROW;
1234 RegionLocations locations = null;
1235 if (useCache) {
1236 locations = getCachedLocation(tableName, metaCacheKey);
1237 if (locations != null && locations.getRegionLocation(replicaId) != null) {
1238 return locations;
1239 }
1240 }
1241
1242
1243 synchronized (metaRegionLock) {
1244
1245
1246 if (useCache) {
1247 locations = getCachedLocation(tableName, metaCacheKey);
1248 if (locations != null && locations.getRegionLocation(replicaId) != null) {
1249 return locations;
1250 }
1251 }
1252
1253
1254 locations = this.registry.getMetaRegionLocation();
1255 if (locations != null) {
1256 cacheLocation(tableName, locations);
1257 }
1258 }
1259 return locations;
1260 }
1261
1262
1263
1264
1265
1266 private RegionLocations locateRegionInMeta(TableName tableName, byte[] row,
1267 boolean useCache, boolean retry, int replicaId) throws IOException {
1268
1269
1270
1271 if (useCache) {
1272 RegionLocations locations = getCachedLocation(tableName, row);
1273 if (locations != null && locations.getRegionLocation(replicaId) != null) {
1274 return locations;
1275 }
1276 }
1277
1278
1279
1280
1281 byte[] metaKey = HRegionInfo.createRegionName(tableName, row, HConstants.NINES, false);
1282
1283 Scan s = new Scan();
1284 s.setReversed(true);
1285 s.withStartRow(metaKey);
1286
1287 if (this.useMetaReplicas) {
1288 s.setConsistency(Consistency.TIMELINE);
1289 }
1290
1291 int localNumRetries = (retry ? numTries : 1);
1292
1293 for (int tries = 0; true; tries++) {
1294 if (tries >= localNumRetries) {
1295 throw new NoServerForRegionException("Unable to find region for " +
1296 Bytes.toStringBinary(row) + " in " + tableName + " after " + tries + " tries.");
1297 }
1298 if (useCache) {
1299 RegionLocations locations = getCachedLocation(tableName, row);
1300 if (locations != null && locations.getRegionLocation(replicaId) != null) {
1301 return locations;
1302 }
1303 } else {
1304
1305
1306
1307 metaCache.clearCache(tableName, row, replicaId);
1308 }
1309
1310
1311 long pauseBase = this.pause;
1312 userRegionLock.lock();
1313 try {
1314 if (useCache) {
1315 RegionLocations locations = getCachedLocation(tableName, row);
1316 if (locations != null && locations.getRegionLocation(replicaId) != null) {
1317 return locations;
1318 }
1319 }
1320 Result regionInfoRow = null;
1321 s.resetMvccReadPoint();
1322 s.setOneRowLimit();
1323 try (ReversedClientScanner rcs =
1324 new ReversedClientScanner(conf, s, TableName.META_TABLE_NAME, this, rpcCallerFactory,
1325 rpcControllerFactory, getMetaLookupPool(),
1326 metaReplicaCallTimeoutScanInMicroSecond)) {
1327 regionInfoRow = rcs.next();
1328 }
1329
1330 if (regionInfoRow == null) {
1331 throw new TableNotFoundException(tableName);
1332 }
1333
1334
1335 RegionLocations locations = MetaTableAccessor.getRegionLocations(regionInfoRow);
1336 if (locations == null || locations.getRegionLocation(replicaId) == null) {
1337 throw new IOException("HRegionInfo was null in " +
1338 tableName + ", row=" + regionInfoRow);
1339 }
1340 HRegionInfo regionInfo = locations.getRegionLocation(replicaId).getRegionInfo();
1341 if (regionInfo == null) {
1342 throw new IOException("HRegionInfo was null or empty in " +
1343 TableName.META_TABLE_NAME + ", row=" + regionInfoRow);
1344 }
1345
1346
1347 if (!regionInfo.getTable().equals(tableName)) {
1348 throw new TableNotFoundException(
1349 "Table '" + tableName + "' was not found, got: " +
1350 regionInfo.getTable() + ".");
1351 }
1352 if (regionInfo.isSplit()) {
1353 throw new RegionOfflineException(
1354 "the only available region for the required row is a split parent," +
1355 " the daughters should be online soon: " + regionInfo.getRegionNameAsString());
1356 }
1357 if (regionInfo.isOffline()) {
1358 throw new RegionOfflineException("the region is offline, could" +
1359 " be caused by a disable table call: " + regionInfo.getRegionNameAsString());
1360 }
1361
1362 ServerName serverName = locations.getRegionLocation(replicaId).getServerName();
1363 if (serverName == null) {
1364 throw new NoServerForRegionException("No server address listed in " +
1365 TableName.META_TABLE_NAME + " for region " + regionInfo.getRegionNameAsString() +
1366 " containing row " + Bytes.toStringBinary(row));
1367 }
1368
1369 if (isDeadServer(serverName)){
1370 throw new RegionServerStoppedException("hbase:meta says the region "+
1371 regionInfo.getRegionNameAsString()+" is managed by the server " + serverName +
1372 ", but it is dead.");
1373 }
1374
1375 cacheLocation(tableName, locations);
1376 return locations;
1377 } catch (TableNotFoundException e) {
1378
1379
1380
1381 throw e;
1382 } catch (IOException e) {
1383 ExceptionUtil.rethrowIfInterrupt(e);
1384
1385 if (e instanceof RemoteException) {
1386 e = ((RemoteException)e).unwrapRemoteException();
1387 }
1388 if (e instanceof CallQueueTooBigException) {
1389
1390 pauseBase = this.pauseForCQTBE;
1391 }
1392 if (tries < localNumRetries - 1) {
1393 if (LOG.isDebugEnabled()) {
1394 LOG.debug("locateRegionInMeta parentTable=" + TableName.META_TABLE_NAME +
1395 ", metaLocation=" + ", attempt=" + tries + " of " + localNumRetries +
1396 " failed; retrying after sleep of " +
1397 ConnectionUtils.getPauseTime(pauseBase, tries) + " because: " + e.getMessage());
1398 }
1399 } else {
1400 throw e;
1401 }
1402
1403 if(!(e instanceof RegionOfflineException ||
1404 e instanceof NoServerForRegionException)) {
1405 relocateRegion(TableName.META_TABLE_NAME, metaKey, replicaId);
1406 }
1407 } finally {
1408 userRegionLock.unlock();
1409 }
1410 try{
1411 Thread.sleep(ConnectionUtils.getPauseTime(pauseBase, tries));
1412 } catch (InterruptedException e) {
1413 throw new InterruptedIOException("Giving up trying to location region in " +
1414 "meta: thread is interrupted.");
1415 }
1416 }
1417 }
1418
1419
1420
1421
1422
1423
1424 @Override
1425 public void cacheLocation(final TableName tableName, final RegionLocations location) {
1426 metaCache.cacheLocation(tableName, location);
1427 }
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437 RegionLocations getCachedLocation(final TableName tableName,
1438 final byte [] row) {
1439 return metaCache.getCachedLocation(tableName, row);
1440 }
1441
1442 public void clearRegionCache(final TableName tableName, byte[] row) {
1443 metaCache.clearCache(tableName, row);
1444 }
1445
1446
1447
1448
1449 @Override
1450 public void clearCaches(final ServerName serverName) {
1451 metaCache.clearCache(serverName);
1452 }
1453
1454 @Override
1455 public void clearRegionCache() {
1456 metaCache.clearCache();
1457 }
1458
1459 @Override
1460 public void clearRegionCache(final TableName tableName) {
1461 metaCache.clearCache(tableName);
1462 }
1463
1464 @Override
1465 public void clearRegionCache(final byte[] tableName) {
1466 clearRegionCache(TableName.valueOf(tableName));
1467 }
1468
1469
1470
1471
1472
1473
1474
1475 private void cacheLocation(final TableName tableName, final ServerName source,
1476 final HRegionLocation location) {
1477 metaCache.cacheLocation(tableName, source, location);
1478 }
1479
1480
1481 private final ConcurrentHashMap<String, Object> stubs =
1482 new ConcurrentHashMap<String, Object>();
1483
1484 private final ConcurrentHashMap<String, String> connectionLock =
1485 new ConcurrentHashMap<String, String>();
1486
1487
1488
1489
1490 static class MasterServiceState {
1491 HConnection connection;
1492 MasterService.BlockingInterface stub;
1493 int userCount;
1494
1495 MasterServiceState (final HConnection connection) {
1496 super();
1497 this.connection = connection;
1498 }
1499
1500 @Override
1501 public String toString() {
1502 return "MasterService";
1503 }
1504
1505 Object getStub() {
1506 return this.stub;
1507 }
1508
1509 void clearStub() {
1510 this.stub = null;
1511 }
1512
1513 boolean isMasterRunning() throws ServiceException {
1514 IsMasterRunningResponse response =
1515 this.stub.isMasterRunning(null, RequestConverter.buildIsMasterRunningRequest());
1516 return response != null? response.getIsMasterRunning(): false;
1517 }
1518 }
1519
1520
1521
1522
1523
1524
1525 abstract class StubMaker {
1526
1527
1528
1529 protected abstract String getServiceName();
1530
1531
1532
1533
1534
1535 protected abstract Object makeStub(final BlockingRpcChannel channel);
1536
1537
1538
1539
1540
1541 protected abstract void isMasterRunning() throws ServiceException;
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551 private Object makeStubNoRetries() throws IOException, KeeperException, ServiceException {
1552 ZooKeeperKeepAliveConnection zkw;
1553 try {
1554 zkw = getKeepAliveZooKeeperWatcher();
1555 } catch (IOException e) {
1556 ExceptionUtil.rethrowIfInterrupt(e);
1557 throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
1558 }
1559 try {
1560 checkIfBaseNodeAvailable(zkw);
1561 ServerName sn = MasterAddressTracker.getMasterAddress(zkw);
1562 if (sn == null) {
1563 String msg = "ZooKeeper available but no active master location found";
1564 LOG.info(msg);
1565 throw new MasterNotRunningException(msg);
1566 }
1567 if (isDeadServer(sn)) {
1568 throw new MasterNotRunningException(sn + " is dead.");
1569 }
1570
1571 String key = getStubKey(getServiceName(),
1572 sn.getHostname(), sn.getPort(), hostnamesCanChange);
1573 connectionLock.putIfAbsent(key, key);
1574 Object stub = null;
1575 synchronized (connectionLock.get(key)) {
1576 stub = stubs.get(key);
1577 if (stub == null) {
1578 BlockingRpcChannel channel = rpcClient.createBlockingRpcChannel(sn, user, rpcTimeout);
1579 stub = makeStub(channel);
1580 isMasterRunning();
1581 stubs.put(key, stub);
1582 }
1583 }
1584 return stub;
1585 } finally {
1586 zkw.close();
1587 }
1588 }
1589
1590
1591
1592
1593
1594
1595 Object makeStub() throws IOException {
1596
1597
1598 synchronized (masterAndZKLock) {
1599 Exception exceptionCaught = null;
1600 if (!closed) {
1601 try {
1602 return makeStubNoRetries();
1603 } catch (IOException e) {
1604 exceptionCaught = e;
1605 } catch (KeeperException e) {
1606 exceptionCaught = e;
1607 } catch (ServiceException e) {
1608 exceptionCaught = e;
1609 }
1610
1611 throw new MasterNotRunningException(exceptionCaught);
1612 } else {
1613 throw new DoNotRetryIOException("Connection was closed while trying to get master");
1614 }
1615 }
1616 }
1617 }
1618
1619
1620
1621
1622 class MasterServiceStubMaker extends StubMaker {
1623 private MasterService.BlockingInterface stub;
1624 @Override
1625 protected String getServiceName() {
1626 return MasterService.getDescriptor().getName();
1627 }
1628
1629 @Override
1630 MasterService.BlockingInterface makeStub() throws IOException {
1631 return (MasterService.BlockingInterface)super.makeStub();
1632 }
1633
1634 @Override
1635 protected Object makeStub(BlockingRpcChannel channel) {
1636 this.stub = MasterService.newBlockingStub(channel);
1637 return this.stub;
1638 }
1639
1640 @Override
1641 protected void isMasterRunning() throws ServiceException {
1642 this.stub.isMasterRunning(null, RequestConverter.buildIsMasterRunningRequest());
1643 }
1644 }
1645
1646 @Override
1647 public AdminService.BlockingInterface getAdmin(final ServerName serverName)
1648 throws IOException {
1649 return getAdmin(serverName, false);
1650 }
1651
1652 @Override
1653
1654 public AdminService.BlockingInterface getAdmin(final ServerName serverName,
1655 final boolean master)
1656 throws IOException {
1657 if (isDeadServer(serverName)) {
1658 throw new RegionServerStoppedException(serverName + " is dead.");
1659 }
1660 String key = getStubKey(AdminService.BlockingInterface.class.getName(),
1661 serverName.getHostname(), serverName.getPort(), this.hostnamesCanChange);
1662 this.connectionLock.putIfAbsent(key, key);
1663 AdminService.BlockingInterface stub = null;
1664 synchronized (this.connectionLock.get(key)) {
1665 stub = (AdminService.BlockingInterface)this.stubs.get(key);
1666 if (stub == null) {
1667 BlockingRpcChannel channel =
1668 this.rpcClient.createBlockingRpcChannel(serverName, user, rpcTimeout);
1669 stub = AdminService.newBlockingStub(channel);
1670 this.stubs.put(key, stub);
1671 }
1672 }
1673 return stub;
1674 }
1675
1676 @Override
1677 public ClientService.BlockingInterface getClient(final ServerName sn)
1678 throws IOException {
1679 if (isDeadServer(sn)) {
1680 throw new RegionServerStoppedException(sn + " is dead.");
1681 }
1682 String key = getStubKey(ClientService.BlockingInterface.class.getName(), sn.getHostname(),
1683 sn.getPort(), this.hostnamesCanChange);
1684 this.connectionLock.putIfAbsent(key, key);
1685 ClientService.BlockingInterface stub = null;
1686 synchronized (this.connectionLock.get(key)) {
1687 stub = (ClientService.BlockingInterface)this.stubs.get(key);
1688 if (stub == null) {
1689 BlockingRpcChannel channel =
1690 this.rpcClient.createBlockingRpcChannel(sn, user, rpcTimeout);
1691 stub = ClientService.newBlockingStub(channel);
1692
1693
1694 this.stubs.put(key, stub);
1695 }
1696 }
1697 return stub;
1698 }
1699
1700 static String getStubKey(final String serviceName,
1701 final String rsHostname,
1702 int port,
1703 boolean resolveHostnames) {
1704
1705
1706
1707
1708
1709
1710 String address = rsHostname;
1711 if (resolveHostnames) {
1712 InetAddress i = new InetSocketAddress(rsHostname, port).getAddress();
1713 if (i != null) {
1714 address = i.getHostAddress() + "-" + rsHostname;
1715 }
1716 }
1717 return serviceName + "@" + address + ":" + port;
1718 }
1719
1720 private ZooKeeperKeepAliveConnection keepAliveZookeeper;
1721 private AtomicInteger keepAliveZookeeperUserCount = new AtomicInteger(0);
1722 private boolean canCloseZKW = true;
1723
1724
1725 private static final long keepAlive = 5 * 60 * 1000;
1726
1727
1728
1729
1730
1731 ZooKeeperKeepAliveConnection getKeepAliveZooKeeperWatcher()
1732 throws IOException {
1733 synchronized (masterAndZKLock) {
1734 if (keepAliveZookeeper == null) {
1735 if (this.closed) {
1736 throw new IOException(toString() + " closed");
1737 }
1738
1739
1740 keepAliveZookeeper = new ZooKeeperKeepAliveConnection(conf, this.toString(), this);
1741 }
1742 keepAliveZookeeperUserCount.addAndGet(1);
1743 keepZooKeeperWatcherAliveUntil = Long.MAX_VALUE;
1744 return keepAliveZookeeper;
1745 }
1746 }
1747
1748 void releaseZooKeeperWatcher(final ZooKeeperWatcher zkw) {
1749 if (zkw == null){
1750 return;
1751 }
1752 if (keepAliveZookeeperUserCount.addAndGet(-1) <= 0 ){
1753 keepZooKeeperWatcherAliveUntil = System.currentTimeMillis() + keepAlive;
1754 }
1755 }
1756
1757 private void closeZooKeeperWatcher() {
1758 synchronized (masterAndZKLock) {
1759 if (keepAliveZookeeper != null) {
1760 LOG.info("Closing zookeeper sessionid=0x" +
1761 Long.toHexString(
1762 keepAliveZookeeper.getRecoverableZooKeeper().getSessionId()));
1763 keepAliveZookeeper.internalClose();
1764 keepAliveZookeeper = null;
1765 }
1766 keepAliveZookeeperUserCount.set(0);
1767 }
1768 }
1769
1770 final MasterServiceState masterServiceState = new MasterServiceState(this);
1771
1772 @Override
1773 public MasterService.BlockingInterface getMaster() throws MasterNotRunningException {
1774 return getKeepAliveMasterService();
1775 }
1776
1777 private void resetMasterServiceState(final MasterServiceState mss) {
1778 mss.userCount++;
1779 }
1780
1781 @Override
1782 public MasterKeepAliveConnection getKeepAliveMasterService()
1783 throws MasterNotRunningException {
1784 synchronized (masterAndZKLock) {
1785 if (!isKeepAliveMasterConnectedAndRunning(this.masterServiceState)) {
1786 MasterServiceStubMaker stubMaker = new MasterServiceStubMaker();
1787 try {
1788 this.masterServiceState.stub = stubMaker.makeStub();
1789 } catch (MasterNotRunningException ex) {
1790 throw ex;
1791 } catch (IOException e) {
1792
1793 throw new MasterNotRunningException(e);
1794 }
1795 }
1796 resetMasterServiceState(this.masterServiceState);
1797 }
1798
1799 final MasterService.BlockingInterface stub = this.masterServiceState.stub;
1800 return new MasterKeepAliveConnection() {
1801 MasterServiceState mss = masterServiceState;
1802 @Override
1803 public MasterProtos.AbortProcedureResponse abortProcedure(
1804 RpcController controller,
1805 MasterProtos.AbortProcedureRequest request) throws ServiceException {
1806 return stub.abortProcedure(controller, request);
1807 }
1808 @Override
1809 public MasterProtos.ListProceduresResponse listProcedures(
1810 RpcController controller,
1811 MasterProtos.ListProceduresRequest request) throws ServiceException {
1812 return stub.listProcedures(controller, request);
1813 }
1814
1815 @Override
1816 public MasterProtos.ClearDeadServersResponse clearDeadServers(
1817 RpcController controller,
1818 MasterProtos.ClearDeadServersRequest request) throws ServiceException {
1819 return stub.clearDeadServers(controller, request);
1820 }
1821
1822 @Override
1823 public AddColumnResponse addColumn(RpcController controller, AddColumnRequest request)
1824 throws ServiceException {
1825 return stub.addColumn(controller, request);
1826 }
1827
1828 @Override
1829 public DeleteColumnResponse deleteColumn(RpcController controller,
1830 DeleteColumnRequest request)
1831 throws ServiceException {
1832 return stub.deleteColumn(controller, request);
1833 }
1834
1835 @Override
1836 public ModifyColumnResponse modifyColumn(RpcController controller,
1837 ModifyColumnRequest request)
1838 throws ServiceException {
1839 return stub.modifyColumn(controller, request);
1840 }
1841
1842 @Override
1843 public MoveRegionResponse moveRegion(RpcController controller,
1844 MoveRegionRequest request) throws ServiceException {
1845 return stub.moveRegion(controller, request);
1846 }
1847
1848 @Override
1849 public DispatchMergingRegionsResponse dispatchMergingRegions(
1850 RpcController controller, DispatchMergingRegionsRequest request)
1851 throws ServiceException {
1852 return stub.dispatchMergingRegions(controller, request);
1853 }
1854
1855 @Override
1856 public AssignRegionResponse assignRegion(RpcController controller,
1857 AssignRegionRequest request) throws ServiceException {
1858 return stub.assignRegion(controller, request);
1859 }
1860
1861 @Override
1862 public UnassignRegionResponse unassignRegion(RpcController controller,
1863 UnassignRegionRequest request) throws ServiceException {
1864 return stub.unassignRegion(controller, request);
1865 }
1866
1867 @Override
1868 public OfflineRegionResponse offlineRegion(RpcController controller,
1869 OfflineRegionRequest request) throws ServiceException {
1870 return stub.offlineRegion(controller, request);
1871 }
1872
1873 @Override
1874 public DeleteTableResponse deleteTable(RpcController controller,
1875 DeleteTableRequest request) throws ServiceException {
1876 return stub.deleteTable(controller, request);
1877 }
1878
1879 @Override
1880 public TruncateTableResponse truncateTable(RpcController controller,
1881 TruncateTableRequest request) throws ServiceException {
1882 return stub.truncateTable(controller, request);
1883 }
1884
1885 @Override
1886 public EnableTableResponse enableTable(RpcController controller,
1887 EnableTableRequest request) throws ServiceException {
1888 return stub.enableTable(controller, request);
1889 }
1890
1891 @Override
1892 public DisableTableResponse disableTable(RpcController controller,
1893 DisableTableRequest request) throws ServiceException {
1894 return stub.disableTable(controller, request);
1895 }
1896
1897 @Override
1898 public ModifyTableResponse modifyTable(RpcController controller,
1899 ModifyTableRequest request) throws ServiceException {
1900 return stub.modifyTable(controller, request);
1901 }
1902
1903 @Override
1904 public CreateTableResponse createTable(RpcController controller,
1905 CreateTableRequest request) throws ServiceException {
1906 return stub.createTable(controller, request);
1907 }
1908
1909 @Override
1910 public ShutdownResponse shutdown(RpcController controller,
1911 ShutdownRequest request) throws ServiceException {
1912 return stub.shutdown(controller, request);
1913 }
1914
1915 @Override
1916 public StopMasterResponse stopMaster(RpcController controller,
1917 StopMasterRequest request) throws ServiceException {
1918 return stub.stopMaster(controller, request);
1919 }
1920
1921 @Override
1922 public MasterProtos.IsInMaintenanceModeResponse isMasterInMaintenanceMode(
1923 final RpcController controller,
1924 final MasterProtos.IsInMaintenanceModeRequest request) throws ServiceException {
1925 return stub.isMasterInMaintenanceMode(controller, request);
1926 }
1927
1928 @Override
1929 public BalanceResponse balance(RpcController controller,
1930 BalanceRequest request) throws ServiceException {
1931 return stub.balance(controller, request);
1932 }
1933
1934 @Override
1935 public SetBalancerRunningResponse setBalancerRunning(
1936 RpcController controller, SetBalancerRunningRequest request)
1937 throws ServiceException {
1938 return stub.setBalancerRunning(controller, request);
1939 }
1940
1941 @Override
1942 public NormalizeResponse normalize(RpcController controller,
1943 NormalizeRequest request) throws ServiceException {
1944 return stub.normalize(controller, request);
1945 }
1946
1947 @Override
1948 public SetNormalizerRunningResponse setNormalizerRunning(
1949 RpcController controller, SetNormalizerRunningRequest request)
1950 throws ServiceException {
1951 return stub.setNormalizerRunning(controller, request);
1952 }
1953
1954 @Override
1955 public RunCatalogScanResponse runCatalogScan(RpcController controller,
1956 RunCatalogScanRequest request) throws ServiceException {
1957 return stub.runCatalogScan(controller, request);
1958 }
1959
1960 @Override
1961 public EnableCatalogJanitorResponse enableCatalogJanitor(
1962 RpcController controller, EnableCatalogJanitorRequest request)
1963 throws ServiceException {
1964 return stub.enableCatalogJanitor(controller, request);
1965 }
1966
1967 @Override
1968 public IsCatalogJanitorEnabledResponse isCatalogJanitorEnabled(
1969 RpcController controller, IsCatalogJanitorEnabledRequest request)
1970 throws ServiceException {
1971 return stub.isCatalogJanitorEnabled(controller, request);
1972 }
1973
1974 @Override
1975 public RunCleanerChoreResponse runCleanerChore(RpcController controller,
1976 RunCleanerChoreRequest request) throws ServiceException {
1977 return stub.runCleanerChore(controller, request);
1978 }
1979
1980 @Override
1981 public SetCleanerChoreRunningResponse setCleanerChoreRunning(RpcController controller,
1982 SetCleanerChoreRunningRequest request) throws ServiceException {
1983 return stub.setCleanerChoreRunning(controller, request);
1984 }
1985
1986 @Override
1987 public IsCleanerChoreEnabledResponse isCleanerChoreEnabled(
1988 RpcController controller, IsCleanerChoreEnabledRequest request)
1989 throws ServiceException {
1990 return stub.isCleanerChoreEnabled(controller, request);
1991 }
1992
1993 @Override
1994 public CoprocessorServiceResponse execMasterService(
1995 RpcController controller, CoprocessorServiceRequest request)
1996 throws ServiceException {
1997 return stub.execMasterService(controller, request);
1998 }
1999
2000 @Override
2001 public SnapshotResponse snapshot(RpcController controller,
2002 SnapshotRequest request) throws ServiceException {
2003 return stub.snapshot(controller, request);
2004 }
2005
2006 @Override
2007 public GetCompletedSnapshotsResponse getCompletedSnapshots(
2008 RpcController controller, GetCompletedSnapshotsRequest request)
2009 throws ServiceException {
2010 return stub.getCompletedSnapshots(controller, request);
2011 }
2012
2013 @Override
2014 public DeleteSnapshotResponse deleteSnapshot(RpcController controller,
2015 DeleteSnapshotRequest request) throws ServiceException {
2016 return stub.deleteSnapshot(controller, request);
2017 }
2018
2019 @Override
2020 public IsSnapshotDoneResponse isSnapshotDone(RpcController controller,
2021 IsSnapshotDoneRequest request) throws ServiceException {
2022 return stub.isSnapshotDone(controller, request);
2023 }
2024
2025 @Override
2026 public RestoreSnapshotResponse restoreSnapshot(
2027 RpcController controller, RestoreSnapshotRequest request)
2028 throws ServiceException {
2029 return stub.restoreSnapshot(controller, request);
2030 }
2031
2032 @Override
2033 public IsRestoreSnapshotDoneResponse isRestoreSnapshotDone(
2034 RpcController controller, IsRestoreSnapshotDoneRequest request)
2035 throws ServiceException {
2036 return stub.isRestoreSnapshotDone(controller, request);
2037 }
2038
2039 @Override
2040 public ExecProcedureResponse execProcedure(
2041 RpcController controller, ExecProcedureRequest request)
2042 throws ServiceException {
2043 return stub.execProcedure(controller, request);
2044 }
2045
2046 @Override
2047 public ExecProcedureResponse execProcedureWithRet(
2048 RpcController controller, ExecProcedureRequest request)
2049 throws ServiceException {
2050 return stub.execProcedureWithRet(controller, request);
2051 }
2052
2053 @Override
2054 public IsProcedureDoneResponse isProcedureDone(RpcController controller,
2055 IsProcedureDoneRequest request) throws ServiceException {
2056 return stub.isProcedureDone(controller, request);
2057 }
2058
2059 @Override
2060 public GetProcedureResultResponse getProcedureResult(RpcController controller,
2061 GetProcedureResultRequest request) throws ServiceException {
2062 return stub.getProcedureResult(controller, request);
2063 }
2064
2065 @Override
2066 public IsMasterRunningResponse isMasterRunning(
2067 RpcController controller, IsMasterRunningRequest request)
2068 throws ServiceException {
2069 return stub.isMasterRunning(controller, request);
2070 }
2071
2072 @Override
2073 public ModifyNamespaceResponse modifyNamespace(RpcController controller,
2074 ModifyNamespaceRequest request)
2075 throws ServiceException {
2076 return stub.modifyNamespace(controller, request);
2077 }
2078
2079 @Override
2080 public CreateNamespaceResponse createNamespace(
2081 RpcController controller, CreateNamespaceRequest request) throws ServiceException {
2082 return stub.createNamespace(controller, request);
2083 }
2084
2085 @Override
2086 public DeleteNamespaceResponse deleteNamespace(
2087 RpcController controller, DeleteNamespaceRequest request) throws ServiceException {
2088 return stub.deleteNamespace(controller, request);
2089 }
2090
2091 @Override
2092 public GetNamespaceDescriptorResponse getNamespaceDescriptor(RpcController controller,
2093 GetNamespaceDescriptorRequest request) throws ServiceException {
2094 return stub.getNamespaceDescriptor(controller, request);
2095 }
2096
2097 @Override
2098 public ListNamespaceDescriptorsResponse listNamespaceDescriptors(RpcController controller,
2099 ListNamespaceDescriptorsRequest request) throws ServiceException {
2100 return stub.listNamespaceDescriptors(controller, request);
2101 }
2102
2103 @Override
2104 public ListTableDescriptorsByNamespaceResponse listTableDescriptorsByNamespace(
2105 RpcController controller, ListTableDescriptorsByNamespaceRequest request)
2106 throws ServiceException {
2107 return stub.listTableDescriptorsByNamespace(controller, request);
2108 }
2109
2110 @Override
2111 public ListTableNamesByNamespaceResponse listTableNamesByNamespace(
2112 RpcController controller, ListTableNamesByNamespaceRequest request)
2113 throws ServiceException {
2114 return stub.listTableNamesByNamespace(controller, request);
2115 }
2116
2117 @Override
2118 public void close() {
2119 release(this.mss);
2120 }
2121
2122 @Override
2123 public GetSchemaAlterStatusResponse getSchemaAlterStatus(
2124 RpcController controller, GetSchemaAlterStatusRequest request)
2125 throws ServiceException {
2126 return stub.getSchemaAlterStatus(controller, request);
2127 }
2128
2129 @Override
2130 public GetTableDescriptorsResponse getTableDescriptors(
2131 RpcController controller, GetTableDescriptorsRequest request)
2132 throws ServiceException {
2133 return stub.getTableDescriptors(controller, request);
2134 }
2135
2136 @Override
2137 public GetTableNamesResponse getTableNames(
2138 RpcController controller, GetTableNamesRequest request)
2139 throws ServiceException {
2140 return stub.getTableNames(controller, request);
2141 }
2142
2143 @Override
2144 public GetClusterStatusResponse getClusterStatus(
2145 RpcController controller, GetClusterStatusRequest request)
2146 throws ServiceException {
2147 return stub.getClusterStatus(controller, request);
2148 }
2149
2150 @Override
2151 public SetQuotaResponse setQuota(RpcController controller, SetQuotaRequest request)
2152 throws ServiceException {
2153 return stub.setQuota(controller, request);
2154 }
2155
2156 @Override
2157 public MajorCompactionTimestampResponse getLastMajorCompactionTimestamp(
2158 RpcController controller, MajorCompactionTimestampRequest request)
2159 throws ServiceException {
2160 return stub.getLastMajorCompactionTimestamp(controller, request);
2161 }
2162
2163 @Override
2164 public MajorCompactionTimestampResponse getLastMajorCompactionTimestampForRegion(
2165 RpcController controller, MajorCompactionTimestampForRegionRequest request)
2166 throws ServiceException {
2167 return stub.getLastMajorCompactionTimestampForRegion(controller, request);
2168 }
2169
2170 @Override
2171 public IsBalancerEnabledResponse isBalancerEnabled(RpcController controller,
2172 IsBalancerEnabledRequest request) throws ServiceException {
2173 return stub.isBalancerEnabled(controller, request);
2174 }
2175
2176 @Override
2177 public MasterProtos.SetSplitOrMergeEnabledResponse setSplitOrMergeEnabled(
2178 RpcController controller,
2179 MasterProtos.SetSplitOrMergeEnabledRequest request) throws ServiceException {
2180 return stub.setSplitOrMergeEnabled(controller, request);
2181 }
2182
2183 @Override
2184 public MasterProtos.IsSplitOrMergeEnabledResponse isSplitOrMergeEnabled(
2185 RpcController controller,
2186 MasterProtos.IsSplitOrMergeEnabledRequest request) throws ServiceException {
2187 return stub.isSplitOrMergeEnabled(controller, request);
2188 }
2189
2190 @Override
2191 public IsNormalizerEnabledResponse isNormalizerEnabled(RpcController controller,
2192 IsNormalizerEnabledRequest request) throws ServiceException {
2193 return stub.isNormalizerEnabled(controller, request);
2194 }
2195
2196 @Override
2197 public SecurityCapabilitiesResponse getSecurityCapabilities(RpcController controller,
2198 SecurityCapabilitiesRequest request) throws ServiceException {
2199 return stub.getSecurityCapabilities(controller, request);
2200 }
2201 };
2202 }
2203
2204
2205 private static void release(MasterServiceState mss) {
2206 if (mss != null && mss.connection != null) {
2207 ((HConnectionImplementation)mss.connection).releaseMaster(mss);
2208 }
2209 }
2210
2211 private boolean isKeepAliveMasterConnectedAndRunning(MasterServiceState mss) {
2212 if (mss.getStub() == null){
2213 return false;
2214 }
2215 try {
2216 return mss.isMasterRunning();
2217 } catch (UndeclaredThrowableException e) {
2218
2219
2220 LOG.info("Master connection is not running anymore", e.getUndeclaredThrowable());
2221 return false;
2222 } catch (ServiceException se) {
2223 LOG.warn("Checking master connection", se);
2224 return false;
2225 }
2226 }
2227
2228 void releaseMaster(MasterServiceState mss) {
2229 if (mss.getStub() == null) return;
2230 synchronized (masterAndZKLock) {
2231 --mss.userCount;
2232 }
2233 }
2234
2235 private void closeMasterService(MasterServiceState mss) {
2236 if (mss.getStub() != null) {
2237 LOG.info("Closing master protocol: " + mss);
2238 mss.clearStub();
2239 }
2240 mss.userCount = 0;
2241 }
2242
2243
2244
2245
2246
2247 private void closeMaster() {
2248 synchronized (masterAndZKLock) {
2249 closeMasterService(masterServiceState);
2250 }
2251 }
2252
2253 void updateCachedLocation(HRegionInfo hri, ServerName source,
2254 ServerName serverName, long seqNum) {
2255 HRegionLocation newHrl = new HRegionLocation(hri, serverName, seqNum);
2256 cacheLocation(hri.getTable(), source, newHrl);
2257 }
2258
2259 @Override
2260 public void deleteCachedRegionLocation(final HRegionLocation location) {
2261 metaCache.clearCache(location);
2262 }
2263
2264 @Override
2265 public void updateCachedLocations(final TableName tableName, byte[] rowkey,
2266 final Object exception, final HRegionLocation source) {
2267 assert source != null;
2268 updateCachedLocations(tableName, source.getRegionInfo().getRegionName()
2269 , rowkey, exception, source.getServerName());
2270 }
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280 @Override
2281 public void updateCachedLocations(final TableName tableName, byte[] regionName, byte[] rowkey,
2282 final Object exception, final ServerName source) {
2283 if (rowkey == null || tableName == null) {
2284 LOG.warn("Coding error, see method javadoc. row=" + (rowkey == null ? "null" : rowkey) +
2285 ", tableName=" + (tableName == null ? "null" : tableName));
2286 return;
2287 }
2288
2289 if (source == null) {
2290
2291 return;
2292 }
2293
2294 if (regionName == null) {
2295
2296 if (metrics != null) {
2297 metrics.incrCacheDroppingExceptions(exception);
2298 }
2299 metaCache.clearCache(tableName, rowkey, source);
2300 return;
2301 }
2302
2303
2304 final RegionLocations oldLocations = getCachedLocation(tableName, rowkey);
2305 HRegionLocation oldLocation = null;
2306 if (oldLocations != null) {
2307 oldLocation = oldLocations.getRegionLocationByRegionName(regionName);
2308 }
2309 if (oldLocation == null || !source.equals(oldLocation.getServerName())) {
2310
2311
2312 return;
2313 }
2314
2315 HRegionInfo regionInfo = oldLocation.getRegionInfo();
2316 Throwable cause = ClientExceptionsUtil.findException(exception);
2317 if (cause != null) {
2318 if (!ClientExceptionsUtil.isMetaClearingException(cause)) {
2319
2320 return;
2321 }
2322
2323 if (cause instanceof RegionMovedException) {
2324 RegionMovedException rme = (RegionMovedException) cause;
2325 if (LOG.isTraceEnabled()) {
2326 LOG.trace("Region " + regionInfo.getRegionNameAsString() + " moved to " +
2327 rme.getHostname() + ":" + rme.getPort() +
2328 " according to " + source.getHostAndPort());
2329 }
2330
2331
2332 updateCachedLocation(
2333 regionInfo, source, rme.getServerName(), rme.getLocationSeqNum());
2334 return;
2335 }
2336 }
2337
2338 if (metrics != null) {
2339 metrics.incrCacheDroppingExceptions(exception);
2340 }
2341
2342
2343
2344 metaCache.clearCache(regionInfo);
2345 }
2346
2347 @Override
2348 public void updateCachedLocations(final byte[] tableName, byte[] rowkey,
2349 final Object exception, final HRegionLocation source) {
2350 updateCachedLocations(TableName.valueOf(tableName), rowkey, exception, source);
2351 }
2352
2353 @Override
2354 @Deprecated
2355 public void processBatch(List<? extends Row> list,
2356 final TableName tableName,
2357 ExecutorService pool,
2358 Object[] results) throws IOException, InterruptedException {
2359
2360
2361
2362 if (results.length != list.size()) {
2363 throw new IllegalArgumentException(
2364 "argument results must be the same size as argument list");
2365 }
2366 processBatchCallback(list, tableName, pool, results, null);
2367 }
2368
2369 @Override
2370 @Deprecated
2371 public void processBatch(List<? extends Row> list,
2372 final byte[] tableName,
2373 ExecutorService pool,
2374 Object[] results) throws IOException, InterruptedException {
2375 processBatch(list, TableName.valueOf(tableName), pool, results);
2376 }
2377
2378
2379
2380
2381
2382
2383
2384
2385 @Override
2386 @Deprecated
2387 public <R> void processBatchCallback(
2388 List<? extends Row> list,
2389 TableName tableName,
2390 ExecutorService pool,
2391 Object[] results,
2392 Batch.Callback<R> callback)
2393 throws IOException, InterruptedException {
2394
2395 AsyncRequestFuture ars = this.asyncProcess.submitAll(
2396 pool, tableName, list, callback, results);
2397 ars.waitUntilDone();
2398 if (ars.hasError()) {
2399 throw ars.getErrors();
2400 }
2401 }
2402
2403 @Override
2404 @Deprecated
2405 public <R> void processBatchCallback(
2406 List<? extends Row> list,
2407 byte[] tableName,
2408 ExecutorService pool,
2409 Object[] results,
2410 Batch.Callback<R> callback)
2411 throws IOException, InterruptedException {
2412 processBatchCallback(list, TableName.valueOf(tableName), pool, results, callback);
2413 }
2414
2415
2416 protected AsyncProcess createAsyncProcess(Configuration conf) {
2417
2418 return new AsyncProcess(this, conf, batchPool, rpcCallerFactory, false, rpcControllerFactory,
2419 writeRpcTimeout);
2420 }
2421
2422 @Override
2423 public AsyncProcess getAsyncProcess() {
2424 return asyncProcess;
2425 }
2426
2427 @Override
2428 public ServerStatisticTracker getStatisticsTracker() {
2429 return this.stats;
2430 }
2431
2432 @Override
2433 public ClientBackoffPolicy getBackoffPolicy() {
2434 return this.backoffPolicy;
2435 }
2436
2437
2438
2439
2440
2441 @VisibleForTesting
2442 int getNumberOfCachedRegionLocations(final TableName tableName) {
2443 return metaCache.getNumberOfCachedRegionLocations(tableName);
2444 }
2445
2446 @Override
2447 @Deprecated
2448 public void setRegionCachePrefetch(final TableName tableName, final boolean enable) {
2449 }
2450
2451 @Override
2452 @Deprecated
2453 public void setRegionCachePrefetch(final byte[] tableName,
2454 final boolean enable) {
2455 }
2456
2457 @Override
2458 @Deprecated
2459 public boolean getRegionCachePrefetch(TableName tableName) {
2460 return false;
2461 }
2462
2463 @Override
2464 @Deprecated
2465 public boolean getRegionCachePrefetch(byte[] tableName) {
2466 return false;
2467 }
2468
2469 @Override
2470 public void abort(final String msg, Throwable t) {
2471 if (t instanceof KeeperException.SessionExpiredException
2472 && keepAliveZookeeper != null) {
2473 synchronized (masterAndZKLock) {
2474 if (keepAliveZookeeper != null) {
2475 LOG.warn("This client just lost it's session with ZooKeeper," +
2476 " closing it." +
2477 " It will be recreated next time someone needs it", t);
2478 closeZooKeeperWatcher();
2479 }
2480 }
2481 } else {
2482 if (t != null) {
2483 LOG.fatal(msg, t);
2484 } else {
2485 LOG.fatal(msg);
2486 }
2487 this.aborted = true;
2488 close();
2489 this.closed = true;
2490 }
2491 }
2492
2493 @Override
2494 public boolean isClosed() {
2495 return this.closed;
2496 }
2497
2498 @Override
2499 public boolean isAborted(){
2500 return this.aborted;
2501 }
2502
2503 @Override
2504 public int getCurrentNrHRS() throws IOException {
2505 return this.registry.getCurrentNrHRS();
2506 }
2507
2508
2509
2510
2511 void incCount() {
2512 ++refCount;
2513 }
2514
2515
2516
2517
2518 void decCount() {
2519 if (refCount > 0) {
2520 --refCount;
2521 }
2522 }
2523
2524
2525
2526
2527
2528
2529 boolean isZeroReference() {
2530 return refCount == 0;
2531 }
2532
2533 void internalClose() {
2534 if (this.closed) {
2535 return;
2536 }
2537 closeMaster();
2538 shutdownPools();
2539 if (this.metrics != null) {
2540 this.metrics.shutdown();
2541 }
2542 this.closed = true;
2543 closeZooKeeperWatcher();
2544 this.stubs.clear();
2545 if (clusterStatusListener != null) {
2546 clusterStatusListener.close();
2547 }
2548 if (rpcClient != null) {
2549 rpcClient.close();
2550 }
2551 }
2552
2553 @Override
2554 public void close() {
2555 if (managed) {
2556 if (aborted) {
2557 ConnectionManager.deleteStaleConnection(this);
2558 } else {
2559 ConnectionManager.deleteConnection(this, false);
2560 }
2561 } else {
2562 internalClose();
2563 }
2564 }
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577 @Override
2578 protected void finalize() throws Throwable {
2579 super.finalize();
2580
2581 refCount = 1;
2582 close();
2583 }
2584
2585
2586
2587
2588 @Deprecated
2589 @Override
2590 public HTableDescriptor[] listTables() throws IOException {
2591 MasterKeepAliveConnection master = getKeepAliveMasterService();
2592 try {
2593 GetTableDescriptorsRequest req =
2594 RequestConverter.buildGetTableDescriptorsRequest((List<TableName>)null);
2595 return ProtobufUtil.getHTableDescriptorArray(master.getTableDescriptors(null, req));
2596 } catch (ServiceException se) {
2597 throw ProtobufUtil.getRemoteException(se);
2598 } finally {
2599 master.close();
2600 }
2601 }
2602
2603
2604
2605
2606 @Deprecated
2607 @Override
2608 public String[] getTableNames() throws IOException {
2609 TableName[] tableNames = listTableNames();
2610 String result[] = new String[tableNames.length];
2611 for (int i = 0; i < tableNames.length; i++) {
2612 result[i] = tableNames[i].getNameAsString();
2613 }
2614 return result;
2615 }
2616
2617
2618
2619
2620 @Deprecated
2621 @Override
2622 public TableName[] listTableNames() throws IOException {
2623 MasterKeepAliveConnection master = getKeepAliveMasterService();
2624 try {
2625 return ProtobufUtil.getTableNameArray(master.getTableNames(null,
2626 GetTableNamesRequest.newBuilder().build())
2627 .getTableNamesList());
2628 } catch (ServiceException se) {
2629 throw ProtobufUtil.getRemoteException(se);
2630 } finally {
2631 master.close();
2632 }
2633 }
2634
2635
2636
2637
2638 @Deprecated
2639 @Override
2640 public HTableDescriptor[] getHTableDescriptorsByTableName(
2641 List<TableName> tableNames) throws IOException {
2642 if (tableNames == null || tableNames.isEmpty()) return new HTableDescriptor[0];
2643 MasterKeepAliveConnection master = getKeepAliveMasterService();
2644 try {
2645 GetTableDescriptorsRequest req =
2646 RequestConverter.buildGetTableDescriptorsRequest(tableNames);
2647 return ProtobufUtil.getHTableDescriptorArray(master.getTableDescriptors(null, req));
2648 } catch (ServiceException se) {
2649 throw ProtobufUtil.getRemoteException(se);
2650 } finally {
2651 master.close();
2652 }
2653 }
2654
2655
2656
2657
2658 @Deprecated
2659 @Override
2660 public HTableDescriptor[] getHTableDescriptors(
2661 List<String> names) throws IOException {
2662 List<TableName> tableNames = new ArrayList<TableName>(names.size());
2663 for(String name : names) {
2664 tableNames.add(TableName.valueOf(name));
2665 }
2666
2667 return getHTableDescriptorsByTableName(tableNames);
2668 }
2669
2670 @Override
2671 public NonceGenerator getNonceGenerator() {
2672 return this.nonceGenerator;
2673 }
2674
2675
2676
2677
2678
2679
2680
2681
2682 @Deprecated
2683 @Override
2684 public HTableDescriptor getHTableDescriptor(final TableName tableName)
2685 throws IOException {
2686 if (tableName == null) return null;
2687 MasterKeepAliveConnection master = getKeepAliveMasterService();
2688 GetTableDescriptorsResponse htds;
2689 try {
2690 GetTableDescriptorsRequest req =
2691 RequestConverter.buildGetTableDescriptorsRequest(tableName);
2692 htds = master.getTableDescriptors(null, req);
2693 } catch (ServiceException se) {
2694 throw ProtobufUtil.getRemoteException(se);
2695 } finally {
2696 master.close();
2697 }
2698 if (!htds.getTableSchemaList().isEmpty()) {
2699 return HTableDescriptor.convert(htds.getTableSchemaList().get(0));
2700 }
2701 throw new TableNotFoundException(tableName.getNameAsString());
2702 }
2703
2704
2705
2706
2707 @Deprecated
2708 @Override
2709 public HTableDescriptor getHTableDescriptor(final byte[] tableName)
2710 throws IOException {
2711 return getHTableDescriptor(TableName.valueOf(tableName));
2712 }
2713
2714 @Override
2715 public RpcRetryingCallerFactory getNewRpcRetryingCallerFactory(Configuration conf) {
2716 return RpcRetryingCallerFactory
2717 .instantiate(conf, this.interceptor, this.getStatisticsTracker());
2718 }
2719
2720 @Override
2721 public boolean isManaged() {
2722 return managed;
2723 }
2724
2725 @Override
2726 public boolean hasCellBlockSupport() {
2727 return this.rpcClient.hasCellBlockSupport();
2728 }
2729
2730 @Override
2731 public ConnectionConfiguration getConnectionConfiguration() {
2732 return this.connectionConfig;
2733 }
2734
2735 @Override
2736 public RpcRetryingCallerFactory getRpcRetryingCallerFactory() {
2737 return this.rpcCallerFactory;
2738 }
2739
2740 @Override
2741 public RpcControllerFactory getRpcControllerFactory() {
2742 return this.rpcControllerFactory;
2743 }
2744 }
2745
2746
2747
2748
2749 static class ServerErrorTracker {
2750
2751 private final ConcurrentMap<ServerName, ServerErrors> errorsByServer =
2752 new ConcurrentHashMap<ServerName, ServerErrors>();
2753 private final long canRetryUntil;
2754 private final int maxRetries;
2755 private final long startTrackingTime;
2756
2757 public ServerErrorTracker(long timeout, int maxRetries) {
2758 this.maxRetries = maxRetries;
2759 this.canRetryUntil = EnvironmentEdgeManager.currentTime() + timeout;
2760 this.startTrackingTime = new Date().getTime();
2761 }
2762
2763
2764
2765
2766 boolean canRetryMore(int numRetry) {
2767
2768 return numRetry < maxRetries || (maxRetries > 1 &&
2769 EnvironmentEdgeManager.currentTime() < this.canRetryUntil);
2770 }
2771
2772
2773
2774
2775
2776
2777
2778
2779 long calculateBackoffTime(ServerName server, long basePause) {
2780 long result;
2781 ServerErrors errorStats = errorsByServer.get(server);
2782 if (errorStats != null) {
2783 result = ConnectionUtils.getPauseTime(basePause, errorStats.retries.get());
2784 } else {
2785 result = 0;
2786 }
2787 return result;
2788 }
2789
2790
2791
2792
2793
2794
2795 void reportServerError(ServerName server) {
2796 ServerErrors errors = errorsByServer.get(server);
2797 if (errors != null) {
2798 errors.addError();
2799 } else {
2800 errors = errorsByServer.putIfAbsent(server, new ServerErrors());
2801 if (errors != null){
2802 errors.addError();
2803 }
2804 }
2805 }
2806
2807 long getStartTrackingTime() {
2808 return startTrackingTime;
2809 }
2810
2811
2812
2813
2814 private static class ServerErrors {
2815 public final AtomicInteger retries = new AtomicInteger(0);
2816
2817 public void addError() {
2818 retries.incrementAndGet();
2819 }
2820 }
2821 }
2822 }