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 HConnectionImplementation(Configuration conf, boolean managed, ExecutorService pool, User user)
646 throws IOException {
647 this(conf, managed, pool, user, null);
648 }
649
650
651
652
653
654
655
656
657
658
659
660
661 HConnectionImplementation(Configuration conf, boolean managed,
662 ExecutorService pool, User user, String clusterId) throws IOException {
663 this.clusterId = clusterId;
664 this.conf = conf;
665 this.user = user;
666 this.batchPool = pool;
667 this.managed = managed;
668 this.connectionConfig = new ConnectionConfiguration(conf);
669 this.closed = false;
670 this.pause = connectionConfig.getPause();
671 this.pauseForCQTBE = connectionConfig.getPauseForCQTBE();
672 this.useMetaReplicas = conf.getBoolean(HConstants.USE_META_REPLICAS,
673 HConstants.DEFAULT_USE_META_REPLICAS);
674 this.metaReplicaCallTimeoutScanInMicroSecond =
675 connectionConfig.getMetaReplicaCallTimeoutMicroSecondScan();
676
677 this.numTries = connectionConfig.getRetriesNumber();
678 this.rpcTimeout = conf.getInt(
679 HConstants.HBASE_RPC_TIMEOUT_KEY,
680 HConstants.DEFAULT_HBASE_RPC_TIMEOUT);
681 this.writeRpcTimeout = conf.getInt(
682 HConstants.HBASE_RPC_WRITE_TIMEOUT_KEY,
683 HConstants.DEFAULT_HBASE_RPC_TIMEOUT);
684 if (conf.getBoolean(CLIENT_NONCES_ENABLED_KEY, true)) {
685 synchronized (nonceGeneratorCreateLock) {
686 if (ConnectionManager.nonceGenerator == null) {
687 ConnectionManager.nonceGenerator = new PerClientRandomNonceGenerator();
688 }
689 this.nonceGenerator = ConnectionManager.nonceGenerator;
690 }
691 } else {
692 this.nonceGenerator = new NoNonceGenerator();
693 }
694
695 this.stats = ServerStatisticTracker.create(conf);
696 this.interceptor = (new RetryingCallerInterceptorFactory(conf)).build();
697 this.rpcControllerFactory = RpcControllerFactory.instantiate(conf);
698 this.rpcCallerFactory = RpcRetryingCallerFactory.instantiate(conf, interceptor, this.stats);
699 this.backoffPolicy = ClientBackoffPolicyFactory.create(conf);
700 this.asyncProcess = createAsyncProcess(this.conf);
701 if (conf.getBoolean(CLIENT_SIDE_METRICS_ENABLED_KEY, false)) {
702 this.metrics = new MetricsConnection(this);
703 } else {
704 this.metrics = null;
705 }
706 this.metaCache = new MetaCache(this.metrics);
707
708 this.hostnamesCanChange = conf.getBoolean(RESOLVE_HOSTNAME_ON_FAIL_KEY, true);
709 boolean shouldListen = conf.getBoolean(HConstants.STATUS_PUBLISHED,
710 HConstants.STATUS_PUBLISHED_DEFAULT);
711 Class<? extends ClusterStatusListener.Listener> listenerClass =
712 conf.getClass(ClusterStatusListener.STATUS_LISTENER_CLASS,
713 ClusterStatusListener.DEFAULT_STATUS_LISTENER_CLASS,
714 ClusterStatusListener.Listener.class);
715
716 try {
717 this.registry = setupRegistry();
718 retrieveClusterId();
719
720 this.rpcClient = RpcClientFactory.createClient(this.conf, this.clusterId, this.metrics);
721
722
723 if (shouldListen) {
724 if (listenerClass == null) {
725 LOG.warn(HConstants.STATUS_PUBLISHED + " is true, but " +
726 ClusterStatusListener.STATUS_LISTENER_CLASS + " is not set - not listening status");
727 } else {
728 clusterStatusListener = new ClusterStatusListener(
729 new ClusterStatusListener.DeadServerHandler() {
730 @Override
731 public void newDead(ServerName sn) {
732 clearCaches(sn);
733 rpcClient.cancelConnections(sn);
734 }
735 }, conf, listenerClass);
736 }
737 }
738 } catch (Throwable e) {
739
740 LOG.debug("connection construction failed", e);
741 close();
742 throw e;
743 }
744 }
745
746
747
748
749 @VisibleForTesting
750 void setUseMetaReplicas(final boolean useMetaReplicas) {
751 this.useMetaReplicas = useMetaReplicas;
752 }
753
754 @Override
755 public HTableInterface getTable(String tableName) throws IOException {
756 return getTable(TableName.valueOf(tableName));
757 }
758
759 @Override
760 public HTableInterface getTable(byte[] tableName) throws IOException {
761 return getTable(TableName.valueOf(tableName));
762 }
763
764 @Override
765 public HTableInterface getTable(TableName tableName) throws IOException {
766 return getTable(tableName, getBatchPool());
767 }
768
769 @Override
770 public HTableInterface getTable(String tableName, ExecutorService pool) throws IOException {
771 return getTable(TableName.valueOf(tableName), pool);
772 }
773
774 @Override
775 public HTableInterface getTable(byte[] tableName, ExecutorService pool) throws IOException {
776 return getTable(TableName.valueOf(tableName), pool);
777 }
778
779 @Override
780 public HTableInterface getTable(TableName tableName, ExecutorService pool) throws IOException {
781 if (managed) {
782 throw new NeedUnmanagedConnectionException();
783 }
784 return new HTable(tableName, this, connectionConfig, rpcCallerFactory, rpcControllerFactory, pool);
785 }
786
787 @Override
788 public BufferedMutator getBufferedMutator(BufferedMutatorParams params) {
789 if (params.getTableName() == null) {
790 throw new IllegalArgumentException("TableName cannot be null.");
791 }
792 if (params.getPool() == null) {
793 params.pool(HTable.getDefaultExecutor(getConfiguration()));
794 }
795 if (params.getWriteBufferSize() == BufferedMutatorParams.UNSET) {
796 params.writeBufferSize(connectionConfig.getWriteBufferSize());
797 }
798 if (params.getMaxKeyValueSize() == BufferedMutatorParams.UNSET) {
799 params.maxKeyValueSize(connectionConfig.getMaxKeyValueSize());
800 }
801 return new BufferedMutatorImpl(this, rpcCallerFactory, rpcControllerFactory, params);
802 }
803
804 @Override
805 public BufferedMutator getBufferedMutator(TableName tableName) {
806 return getBufferedMutator(new BufferedMutatorParams(tableName));
807 }
808
809 @Override
810 public RegionLocator getRegionLocator(TableName tableName) throws IOException {
811 return new HRegionLocator(tableName, this);
812 }
813
814 @Override
815 public Admin getAdmin() throws IOException {
816 if (managed) {
817 throw new NeedUnmanagedConnectionException();
818 }
819 return new HBaseAdmin(this);
820 }
821
822 @Override
823 public MetricsConnection getConnectionMetrics() {
824 return this.metrics;
825 }
826
827 private ExecutorService getBatchPool() {
828 if (batchPool == null) {
829 synchronized (this) {
830 if (batchPool == null) {
831 this.batchPool = getThreadPool(conf.getInt("hbase.hconnection.threads.max", 256),
832 conf.getInt("hbase.hconnection.threads.core", 256), "-shared-", null);
833 this.cleanupPool = true;
834 }
835 }
836 }
837 return this.batchPool;
838 }
839
840 private ExecutorService getThreadPool(int maxThreads, int coreThreads, String nameHint,
841 BlockingQueue<Runnable> passedWorkQueue) {
842
843 if (maxThreads == 0) {
844 maxThreads = Runtime.getRuntime().availableProcessors() * 8;
845 }
846 if (coreThreads == 0) {
847 coreThreads = Runtime.getRuntime().availableProcessors() * 8;
848 }
849 long keepAliveTime = conf.getLong("hbase.hconnection.threads.keepalivetime", 60);
850 BlockingQueue<Runnable> workQueue = passedWorkQueue;
851 if (workQueue == null) {
852 workQueue =
853 new LinkedBlockingQueue<Runnable>(maxThreads *
854 conf.getInt(HConstants.HBASE_CLIENT_MAX_TOTAL_TASKS,
855 HConstants.DEFAULT_HBASE_CLIENT_MAX_TOTAL_TASKS));
856 }
857 ThreadPoolExecutor tpe = new ThreadPoolExecutor(
858 coreThreads,
859 maxThreads,
860 keepAliveTime,
861 TimeUnit.SECONDS,
862 workQueue,
863 Threads.newDaemonThreadFactory(toString() + nameHint));
864 tpe.allowCoreThreadTimeOut(true);
865 return tpe;
866 }
867
868 private ExecutorService getMetaLookupPool() {
869 if (this.metaLookupPool == null) {
870 synchronized (this) {
871 if (this.metaLookupPool == null) {
872
873
874
875
876 this.metaLookupPool = getThreadPool(
877 conf.getInt("hbase.hconnection.meta.lookup.threads.max", 128),
878 conf.getInt("hbase.hconnection.meta.lookup.threads.core", 10),
879 "-metaLookup-shared-", new LinkedBlockingQueue<Runnable>());
880 }
881 }
882 }
883 return this.metaLookupPool;
884 }
885
886 protected ExecutorService getCurrentMetaLookupPool() {
887 return metaLookupPool;
888 }
889
890 protected ExecutorService getCurrentBatchPool() {
891 return batchPool;
892 }
893
894 private void shutdownPools() {
895 if (this.cleanupPool && this.batchPool != null && !this.batchPool.isShutdown()) {
896 shutdownBatchPool(this.batchPool);
897 }
898 if (this.metaLookupPool != null && !this.metaLookupPool.isShutdown()) {
899 shutdownBatchPool(this.metaLookupPool);
900 }
901 }
902
903 private void shutdownBatchPool(ExecutorService pool) {
904 pool.shutdown();
905 try {
906 if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
907 pool.shutdownNow();
908 }
909 } catch (InterruptedException e) {
910 pool.shutdownNow();
911 }
912 }
913
914
915
916
917
918 private Registry setupRegistry() throws IOException {
919 return RegistryFactory.getRegistry(this);
920 }
921
922
923
924
925 @VisibleForTesting
926 RpcClient getRpcClient() {
927 return rpcClient;
928 }
929
930
931
932
933 @Override
934 public String toString(){
935 return "hconnection-0x" + Integer.toHexString(hashCode());
936 }
937
938 protected String clusterId = null;
939
940 void retrieveClusterId() {
941 if (clusterId != null) return;
942 this.clusterId = this.registry.getClusterId();
943 if (clusterId == null) {
944 clusterId = HConstants.CLUSTER_ID_DEFAULT;
945 LOG.debug("clusterid came back null, using default " + clusterId);
946 }
947 }
948
949 @Override
950 public Configuration getConfiguration() {
951 return this.conf;
952 }
953
954 private void checkIfBaseNodeAvailable(ZooKeeperWatcher zkw)
955 throws MasterNotRunningException {
956 String errorMsg;
957 try {
958 if (ZKUtil.checkExists(zkw, zkw.baseZNode) == -1) {
959 errorMsg = "The node " + zkw.baseZNode+" is not in ZooKeeper. "
960 + "It should have been written by the master. "
961 + "Check the value configured in 'zookeeper.znode.parent'. "
962 + "There could be a mismatch with the one configured in the master.";
963 LOG.error(errorMsg);
964 throw new MasterNotRunningException(errorMsg);
965 }
966 } catch (KeeperException e) {
967 errorMsg = "Can't get connection to ZooKeeper: " + e.getMessage();
968 LOG.error(errorMsg);
969 throw new MasterNotRunningException(errorMsg, e);
970 }
971 }
972
973
974
975
976
977
978 @Deprecated
979 @Override
980 public boolean isMasterRunning()
981 throws MasterNotRunningException, ZooKeeperConnectionException {
982
983
984
985 MasterKeepAliveConnection m = getKeepAliveMasterService();
986 m.close();
987 return true;
988 }
989
990 @Override
991 public HRegionLocation getRegionLocation(final TableName tableName,
992 final byte [] row, boolean reload)
993 throws IOException {
994 return reload? relocateRegion(tableName, row): locateRegion(tableName, row);
995 }
996
997 @Override
998 public HRegionLocation getRegionLocation(final byte[] tableName,
999 final byte [] row, boolean reload)
1000 throws IOException {
1001 return getRegionLocation(TableName.valueOf(tableName), row, reload);
1002 }
1003
1004 @Override
1005 public boolean isTableEnabled(TableName tableName) throws IOException {
1006 return this.registry.isTableOnlineState(tableName, true);
1007 }
1008
1009 @Override
1010 public boolean isTableEnabled(byte[] tableName) throws IOException {
1011 return isTableEnabled(TableName.valueOf(tableName));
1012 }
1013
1014 @Override
1015 public boolean isTableDisabled(TableName tableName) throws IOException {
1016 return this.registry.isTableOnlineState(tableName, false);
1017 }
1018
1019 @Override
1020 public boolean isTableDisabled(byte[] tableName) throws IOException {
1021 return isTableDisabled(TableName.valueOf(tableName));
1022 }
1023
1024 @Override
1025 public boolean isTableAvailable(final TableName tableName) throws IOException {
1026 final AtomicBoolean available = new AtomicBoolean(true);
1027 final AtomicInteger regionCount = new AtomicInteger(0);
1028 MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
1029 @Override
1030 public boolean processRow(Result row) throws IOException {
1031 HRegionInfo info = MetaScanner.getHRegionInfo(row);
1032 if (info != null && !info.isSplitParent()) {
1033 if (tableName.equals(info.getTable())) {
1034 ServerName server = HRegionInfo.getServerName(row);
1035 if (server == null) {
1036 available.set(false);
1037 return false;
1038 }
1039 regionCount.incrementAndGet();
1040 } else if (tableName.compareTo(info.getTable()) < 0) {
1041
1042 return false;
1043 }
1044 }
1045 return true;
1046 }
1047 };
1048 MetaScanner.metaScan(this, visitor, tableName);
1049 return available.get() && (regionCount.get() > 0);
1050 }
1051
1052 @Override
1053 public boolean isTableAvailable(final byte[] tableName) throws IOException {
1054 return isTableAvailable(TableName.valueOf(tableName));
1055 }
1056
1057 @Override
1058 public boolean isTableAvailable(final TableName tableName, final byte[][] splitKeys)
1059 throws IOException {
1060 final AtomicBoolean available = new AtomicBoolean(true);
1061 final AtomicInteger regionCount = new AtomicInteger(0);
1062 MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
1063 @Override
1064 public boolean processRow(Result row) throws IOException {
1065 HRegionInfo info = MetaScanner.getHRegionInfo(row);
1066 if (info != null && !info.isSplitParent()) {
1067 if (tableName.equals(info.getTable())) {
1068 ServerName server = HRegionInfo.getServerName(row);
1069 if (server == null) {
1070 available.set(false);
1071 return false;
1072 }
1073 if (!Bytes.equals(info.getStartKey(), HConstants.EMPTY_BYTE_ARRAY)) {
1074 for (byte[] splitKey : splitKeys) {
1075
1076 if (Bytes.equals(info.getStartKey(), splitKey)) {
1077 regionCount.incrementAndGet();
1078 break;
1079 }
1080 }
1081 } else {
1082
1083 regionCount.incrementAndGet();
1084 }
1085 } else if (tableName.compareTo(info.getTable()) < 0) {
1086
1087 return false;
1088 }
1089 }
1090 return true;
1091 }
1092 };
1093 MetaScanner.metaScan(this, visitor, tableName);
1094
1095 return available.get() && (regionCount.get() == splitKeys.length + 1);
1096 }
1097
1098 @Override
1099 public boolean isTableAvailable(final byte[] tableName, final byte[][] splitKeys)
1100 throws IOException {
1101 return isTableAvailable(TableName.valueOf(tableName), splitKeys);
1102 }
1103
1104 @Override
1105 public HRegionLocation locateRegion(final byte[] regionName) throws IOException {
1106 RegionLocations locations = locateRegion(HRegionInfo.getTable(regionName),
1107 HRegionInfo.getStartKey(regionName), false, true);
1108 return locations == null ? null : locations.getRegionLocation();
1109 }
1110
1111 @Override
1112 public boolean isDeadServer(ServerName sn) {
1113 if (clusterStatusListener == null) {
1114 return false;
1115 } else {
1116 return clusterStatusListener.isDeadServer(sn);
1117 }
1118 }
1119
1120 @Override
1121 public List<HRegionLocation> locateRegions(final TableName tableName)
1122 throws IOException {
1123 return locateRegions (tableName, false, true);
1124 }
1125
1126 @Override
1127 public List<HRegionLocation> locateRegions(final byte[] tableName)
1128 throws IOException {
1129 return locateRegions(TableName.valueOf(tableName));
1130 }
1131
1132 @Override
1133 public List<HRegionLocation> locateRegions(final TableName tableName,
1134 final boolean useCache, final boolean offlined) throws IOException {
1135 NavigableMap<HRegionInfo, ServerName> regions = MetaScanner.allTableRegions(this, tableName);
1136 final List<HRegionLocation> locations = new ArrayList<HRegionLocation>();
1137 for (HRegionInfo regionInfo : regions.keySet()) {
1138 if (!RegionReplicaUtil.isDefaultReplica(regionInfo)) {
1139 continue;
1140 }
1141 RegionLocations list = locateRegion(tableName, regionInfo.getStartKey(), useCache, true);
1142 if (list != null) {
1143 for (HRegionLocation loc : list.getRegionLocations()) {
1144 if (loc != null) {
1145 locations.add(loc);
1146 }
1147 }
1148 }
1149 }
1150 return locations;
1151 }
1152
1153 @Override
1154 public List<HRegionLocation> locateRegions(final byte[] tableName,
1155 final boolean useCache, final boolean offlined) throws IOException {
1156 return locateRegions(TableName.valueOf(tableName), useCache, offlined);
1157 }
1158
1159 @Override
1160 public HRegionLocation locateRegion(
1161 final TableName tableName, final byte[] row) throws IOException{
1162 RegionLocations locations = locateRegion(tableName, row, true, true);
1163 return locations == null ? null : locations.getRegionLocation();
1164 }
1165
1166 @Override
1167 public HRegionLocation locateRegion(final byte[] tableName,
1168 final byte [] row)
1169 throws IOException{
1170 return locateRegion(TableName.valueOf(tableName), row);
1171 }
1172
1173 @Override
1174 public HRegionLocation relocateRegion(final TableName tableName,
1175 final byte [] row) throws IOException{
1176 RegionLocations locations = relocateRegion(tableName, row,
1177 RegionReplicaUtil.DEFAULT_REPLICA_ID);
1178 return locations == null ? null :
1179 locations.getRegionLocation(RegionReplicaUtil.DEFAULT_REPLICA_ID);
1180 }
1181
1182 @Override
1183 public RegionLocations relocateRegion(final TableName tableName,
1184 final byte [] row, int replicaId) throws IOException{
1185
1186
1187
1188 if (!tableName.equals(TableName.META_TABLE_NAME) && isTableDisabled(tableName)) {
1189 throw new TableNotEnabledException(tableName.getNameAsString() + " is disabled.");
1190 }
1191
1192 return locateRegion(tableName, row, false, true, replicaId);
1193 }
1194
1195 @Override
1196 public HRegionLocation relocateRegion(final byte[] tableName,
1197 final byte [] row) throws IOException {
1198 return relocateRegion(TableName.valueOf(tableName), row);
1199 }
1200
1201 @Override
1202 public RegionLocations locateRegion(final TableName tableName,
1203 final byte [] row, boolean useCache, boolean retry)
1204 throws IOException {
1205 return locateRegion(tableName, row, useCache, retry, RegionReplicaUtil.DEFAULT_REPLICA_ID);
1206 }
1207
1208 @Override
1209 public RegionLocations locateRegion(final TableName tableName,
1210 final byte [] row, boolean useCache, boolean retry, int replicaId)
1211 throws IOException {
1212 if (this.closed) throw new DoNotRetryIOException(toString() + " closed");
1213 if (tableName== null || tableName.getName().length == 0) {
1214 throw new IllegalArgumentException(
1215 "table name cannot be null or zero length");
1216 }
1217 if (tableName.equals(TableName.META_TABLE_NAME)) {
1218 return locateMeta(tableName, useCache, replicaId);
1219 } else {
1220
1221 return locateRegionInMeta(tableName, row, useCache, retry, replicaId);
1222 }
1223 }
1224
1225 private volatile RegionLocations metaLocations = null;
1226 private volatile long lastMetaLookupTime = EnvironmentEdgeManager.currentTime();
1227
1228 private final static long META_LOOKUP_CACHE_INTERVAL = 10000;
1229
1230 private RegionLocations locateMeta(final TableName tableName,
1231 boolean useCache, int replicaId) throws IOException {
1232
1233
1234
1235 if (useCache) {
1236 long now = EnvironmentEdgeManager.currentTime();
1237 if (now - lastMetaLookupTime < META_LOOKUP_CACHE_INTERVAL) {
1238 if (metaLocations != null &&
1239 metaLocations.getRegionLocation(replicaId) != null) {
1240 return metaLocations;
1241 }
1242 } else {
1243 useCache = false;
1244 }
1245 }
1246
1247 synchronized (metaRegionLock) {
1248
1249
1250 if (useCache) {
1251 if (metaLocations != null &&
1252 metaLocations.getRegionLocation(replicaId) != null) {
1253 return metaLocations;
1254 }
1255 }
1256
1257 metaLocations = this.registry.getMetaRegionLocation();
1258 lastMetaLookupTime = EnvironmentEdgeManager.currentTime();
1259 if (metaLocations != null &&
1260 metaLocations.getRegionLocation(replicaId) != null) {
1261 return metaLocations;
1262 }
1263 return null;
1264 }
1265 }
1266
1267
1268
1269
1270
1271 private RegionLocations locateRegionInMeta(TableName tableName, byte[] row,
1272 boolean useCache, boolean retry, int replicaId) throws IOException {
1273
1274
1275
1276 if (useCache) {
1277 RegionLocations locations = getCachedLocation(tableName, row);
1278 if (locations != null && locations.getRegionLocation(replicaId) != null) {
1279 return locations;
1280 }
1281 }
1282
1283
1284
1285
1286 byte[] metaKey = HRegionInfo.createRegionName(tableName, row, HConstants.NINES, false);
1287
1288 Scan s = new Scan();
1289 s.setReversed(true);
1290 s.withStartRow(metaKey);
1291
1292 if (this.useMetaReplicas) {
1293 s.setConsistency(Consistency.TIMELINE);
1294 }
1295
1296 int localNumRetries = (retry ? numTries : 1);
1297
1298 for (int tries = 0; true; tries++) {
1299 if (tries >= localNumRetries) {
1300 throw new NoServerForRegionException("Unable to find region for " +
1301 Bytes.toStringBinary(row) + " in " + tableName + " after " + tries + " tries.");
1302 }
1303 if (useCache) {
1304 RegionLocations locations = getCachedLocation(tableName, row);
1305 if (locations != null && locations.getRegionLocation(replicaId) != null) {
1306 return locations;
1307 }
1308 } else {
1309
1310
1311
1312 metaCache.clearCache(tableName, row, replicaId);
1313 }
1314
1315
1316 long pauseBase = this.pause;
1317 userRegionLock.lock();
1318 try {
1319 if (useCache) {
1320 RegionLocations locations = getCachedLocation(tableName, row);
1321 if (locations != null && locations.getRegionLocation(replicaId) != null) {
1322 return locations;
1323 }
1324 }
1325 Result regionInfoRow = null;
1326 s.resetMvccReadPoint();
1327 s.setOneRowLimit();
1328 try (ReversedClientScanner rcs =
1329 new ReversedClientScanner(conf, s, TableName.META_TABLE_NAME, this, rpcCallerFactory,
1330 rpcControllerFactory, getMetaLookupPool(),
1331 metaReplicaCallTimeoutScanInMicroSecond)) {
1332 regionInfoRow = rcs.next();
1333 }
1334
1335 if (regionInfoRow == null) {
1336 throw new TableNotFoundException(tableName);
1337 }
1338
1339
1340 RegionLocations locations = MetaTableAccessor.getRegionLocations(regionInfoRow);
1341 if (locations == null || locations.getRegionLocation(replicaId) == null) {
1342 throw new IOException("HRegionInfo was null in " +
1343 tableName + ", row=" + regionInfoRow);
1344 }
1345 HRegionInfo regionInfo = locations.getRegionLocation(replicaId).getRegionInfo();
1346 if (regionInfo == null) {
1347 throw new IOException("HRegionInfo was null or empty in " +
1348 TableName.META_TABLE_NAME + ", row=" + regionInfoRow);
1349 }
1350
1351
1352 if (!regionInfo.getTable().equals(tableName)) {
1353 throw new TableNotFoundException(
1354 "Table '" + tableName + "' was not found, got: " +
1355 regionInfo.getTable() + ".");
1356 }
1357 if (regionInfo.isSplit()) {
1358 throw new RegionOfflineException(
1359 "the only available region for the required row is a split parent," +
1360 " the daughters should be online soon: " + regionInfo.getRegionNameAsString());
1361 }
1362 if (regionInfo.isOffline()) {
1363 throw new RegionOfflineException("the region is offline, could" +
1364 " be caused by a disable table call: " + regionInfo.getRegionNameAsString());
1365 }
1366
1367 ServerName serverName = locations.getRegionLocation(replicaId).getServerName();
1368 if (serverName == null) {
1369 throw new NoServerForRegionException("No server address listed in " +
1370 TableName.META_TABLE_NAME + " for region " + regionInfo.getRegionNameAsString() +
1371 " containing row " + Bytes.toStringBinary(row));
1372 }
1373
1374 if (isDeadServer(serverName)){
1375 throw new RegionServerStoppedException("hbase:meta says the region "+
1376 regionInfo.getRegionNameAsString()+" is managed by the server " + serverName +
1377 ", but it is dead.");
1378 }
1379
1380 cacheLocation(tableName, locations);
1381 return locations;
1382 } catch (TableNotFoundException e) {
1383
1384
1385
1386 throw e;
1387 } catch (IOException e) {
1388 ExceptionUtil.rethrowIfInterrupt(e);
1389
1390 if (e instanceof RemoteException) {
1391 e = ((RemoteException)e).unwrapRemoteException();
1392 }
1393 if (e instanceof CallQueueTooBigException) {
1394
1395 pauseBase = this.pauseForCQTBE;
1396 }
1397 if (tries < localNumRetries - 1) {
1398 if (LOG.isDebugEnabled()) {
1399 LOG.debug("locateRegionInMeta parentTable=" + TableName.META_TABLE_NAME +
1400 ", metaLocation=" + ", attempt=" + tries + " of " + localNumRetries +
1401 " failed; retrying after sleep of " +
1402 ConnectionUtils.getPauseTime(pauseBase, tries) + " because: " + e.getMessage());
1403 }
1404 } else {
1405 throw e;
1406 }
1407
1408 if(!(e instanceof RegionOfflineException ||
1409 e instanceof NoServerForRegionException)) {
1410 relocateRegion(TableName.META_TABLE_NAME, metaKey, replicaId);
1411 }
1412 } finally {
1413 userRegionLock.unlock();
1414 }
1415 try{
1416 Thread.sleep(ConnectionUtils.getPauseTime(pauseBase, tries));
1417 } catch (InterruptedException e) {
1418 throw new InterruptedIOException("Giving up trying to location region in " +
1419 "meta: thread is interrupted.");
1420 }
1421 }
1422 }
1423
1424
1425
1426
1427
1428
1429 @Override
1430 public void cacheLocation(final TableName tableName, final RegionLocations location) {
1431 metaCache.cacheLocation(tableName, location);
1432 }
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442 RegionLocations getCachedLocation(final TableName tableName,
1443 final byte [] row) {
1444 return metaCache.getCachedLocation(tableName, row);
1445 }
1446
1447 public void clearRegionCache(final TableName tableName, byte[] row) {
1448 metaCache.clearCache(tableName, row);
1449 }
1450
1451
1452
1453
1454 @Override
1455 public void clearCaches(final ServerName serverName) {
1456 metaCache.clearCache(serverName);
1457 }
1458
1459 @Override
1460 public void clearRegionCache() {
1461 metaCache.clearCache();
1462 }
1463
1464 @Override
1465 public void clearRegionCache(final TableName tableName) {
1466 metaCache.clearCache(tableName);
1467 }
1468
1469 @Override
1470 public void clearRegionCache(final byte[] tableName) {
1471 clearRegionCache(TableName.valueOf(tableName));
1472 }
1473
1474
1475
1476
1477
1478
1479
1480 private void cacheLocation(final TableName tableName, final ServerName source,
1481 final HRegionLocation location) {
1482 metaCache.cacheLocation(tableName, source, location);
1483 }
1484
1485
1486 private final ConcurrentHashMap<String, Object> stubs =
1487 new ConcurrentHashMap<String, Object>();
1488
1489 private final ConcurrentHashMap<String, String> connectionLock =
1490 new ConcurrentHashMap<String, String>();
1491
1492
1493
1494
1495 static class MasterServiceState {
1496 HConnection connection;
1497 MasterService.BlockingInterface stub;
1498 int userCount;
1499
1500 MasterServiceState (final HConnection connection) {
1501 super();
1502 this.connection = connection;
1503 }
1504
1505 @Override
1506 public String toString() {
1507 return "MasterService";
1508 }
1509
1510 Object getStub() {
1511 return this.stub;
1512 }
1513
1514 void clearStub() {
1515 this.stub = null;
1516 }
1517
1518 boolean isMasterRunning() throws ServiceException {
1519 IsMasterRunningResponse response =
1520 this.stub.isMasterRunning(null, RequestConverter.buildIsMasterRunningRequest());
1521 return response != null? response.getIsMasterRunning(): false;
1522 }
1523 }
1524
1525
1526
1527
1528
1529
1530 abstract class StubMaker {
1531
1532
1533
1534 protected abstract String getServiceName();
1535
1536
1537
1538
1539
1540 protected abstract Object makeStub(final BlockingRpcChannel channel);
1541
1542
1543
1544
1545
1546 protected abstract void isMasterRunning() throws ServiceException;
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556 private Object makeStubNoRetries() throws IOException, KeeperException, ServiceException {
1557 ZooKeeperKeepAliveConnection zkw;
1558 try {
1559 zkw = getKeepAliveZooKeeperWatcher();
1560 } catch (IOException e) {
1561 ExceptionUtil.rethrowIfInterrupt(e);
1562 throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
1563 }
1564 try {
1565 checkIfBaseNodeAvailable(zkw);
1566 ServerName sn = MasterAddressTracker.getMasterAddress(zkw);
1567 if (sn == null) {
1568 String msg = "ZooKeeper available but no active master location found";
1569 LOG.info(msg);
1570 throw new MasterNotRunningException(msg);
1571 }
1572 if (isDeadServer(sn)) {
1573 throw new MasterNotRunningException(sn + " is dead.");
1574 }
1575
1576 String key = getStubKey(getServiceName(),
1577 sn.getHostname(), sn.getPort(), hostnamesCanChange);
1578 connectionLock.putIfAbsent(key, key);
1579 Object stub = null;
1580 synchronized (connectionLock.get(key)) {
1581 stub = stubs.get(key);
1582 if (stub == null) {
1583 BlockingRpcChannel channel = rpcClient.createBlockingRpcChannel(sn, user, rpcTimeout);
1584 stub = makeStub(channel);
1585 isMasterRunning();
1586 stubs.put(key, stub);
1587 }
1588 }
1589 return stub;
1590 } finally {
1591 zkw.close();
1592 }
1593 }
1594
1595
1596
1597
1598
1599
1600 Object makeStub() throws IOException {
1601
1602
1603 synchronized (masterAndZKLock) {
1604 Exception exceptionCaught = null;
1605 if (!closed) {
1606 try {
1607 return makeStubNoRetries();
1608 } catch (IOException e) {
1609 exceptionCaught = e;
1610 } catch (KeeperException e) {
1611 exceptionCaught = e;
1612 } catch (ServiceException e) {
1613 exceptionCaught = e;
1614 }
1615
1616 throw new MasterNotRunningException(exceptionCaught);
1617 } else {
1618 throw new DoNotRetryIOException("Connection was closed while trying to get master");
1619 }
1620 }
1621 }
1622 }
1623
1624
1625
1626
1627 class MasterServiceStubMaker extends StubMaker {
1628 private MasterService.BlockingInterface stub;
1629 @Override
1630 protected String getServiceName() {
1631 return MasterService.getDescriptor().getName();
1632 }
1633
1634 @Override
1635 MasterService.BlockingInterface makeStub() throws IOException {
1636 return (MasterService.BlockingInterface)super.makeStub();
1637 }
1638
1639 @Override
1640 protected Object makeStub(BlockingRpcChannel channel) {
1641 this.stub = MasterService.newBlockingStub(channel);
1642 return this.stub;
1643 }
1644
1645 @Override
1646 protected void isMasterRunning() throws ServiceException {
1647 this.stub.isMasterRunning(null, RequestConverter.buildIsMasterRunningRequest());
1648 }
1649 }
1650
1651 @Override
1652 public AdminService.BlockingInterface getAdmin(final ServerName serverName)
1653 throws IOException {
1654 return getAdmin(serverName, false);
1655 }
1656
1657 @Override
1658
1659 public AdminService.BlockingInterface getAdmin(final ServerName serverName,
1660 final boolean master)
1661 throws IOException {
1662 if (isDeadServer(serverName)) {
1663 throw new RegionServerStoppedException(serverName + " is dead.");
1664 }
1665 String key = getStubKey(AdminService.BlockingInterface.class.getName(),
1666 serverName.getHostname(), serverName.getPort(), this.hostnamesCanChange);
1667 this.connectionLock.putIfAbsent(key, key);
1668 AdminService.BlockingInterface stub = null;
1669 synchronized (this.connectionLock.get(key)) {
1670 stub = (AdminService.BlockingInterface)this.stubs.get(key);
1671 if (stub == null) {
1672 BlockingRpcChannel channel =
1673 this.rpcClient.createBlockingRpcChannel(serverName, user, rpcTimeout);
1674 stub = AdminService.newBlockingStub(channel);
1675 this.stubs.put(key, stub);
1676 }
1677 }
1678 return stub;
1679 }
1680
1681 @Override
1682 public ClientService.BlockingInterface getClient(final ServerName sn)
1683 throws IOException {
1684 if (isDeadServer(sn)) {
1685 throw new RegionServerStoppedException(sn + " is dead.");
1686 }
1687 String key = getStubKey(ClientService.BlockingInterface.class.getName(), sn.getHostname(),
1688 sn.getPort(), this.hostnamesCanChange);
1689 this.connectionLock.putIfAbsent(key, key);
1690 ClientService.BlockingInterface stub = null;
1691 synchronized (this.connectionLock.get(key)) {
1692 stub = (ClientService.BlockingInterface)this.stubs.get(key);
1693 if (stub == null) {
1694 BlockingRpcChannel channel =
1695 this.rpcClient.createBlockingRpcChannel(sn, user, rpcTimeout);
1696 stub = ClientService.newBlockingStub(channel);
1697
1698
1699 this.stubs.put(key, stub);
1700 }
1701 }
1702 return stub;
1703 }
1704
1705 static String getStubKey(final String serviceName,
1706 final String rsHostname,
1707 int port,
1708 boolean resolveHostnames) {
1709
1710
1711
1712
1713
1714
1715 String address = rsHostname;
1716 if (resolveHostnames) {
1717 InetAddress i = new InetSocketAddress(rsHostname, port).getAddress();
1718 if (i != null) {
1719 address = i.getHostAddress() + "-" + rsHostname;
1720 }
1721 }
1722 return serviceName + "@" + address + ":" + port;
1723 }
1724
1725 private ZooKeeperKeepAliveConnection keepAliveZookeeper;
1726 private AtomicInteger keepAliveZookeeperUserCount = new AtomicInteger(0);
1727 private boolean canCloseZKW = true;
1728
1729
1730 private static final long keepAlive = 5 * 60 * 1000;
1731
1732
1733
1734
1735
1736 ZooKeeperKeepAliveConnection getKeepAliveZooKeeperWatcher()
1737 throws IOException {
1738 synchronized (masterAndZKLock) {
1739 if (keepAliveZookeeper == null) {
1740 if (this.closed) {
1741 throw new IOException(toString() + " closed");
1742 }
1743
1744
1745 keepAliveZookeeper = new ZooKeeperKeepAliveConnection(conf, this.toString(), this);
1746 }
1747 keepAliveZookeeperUserCount.addAndGet(1);
1748 keepZooKeeperWatcherAliveUntil = Long.MAX_VALUE;
1749 return keepAliveZookeeper;
1750 }
1751 }
1752
1753 void releaseZooKeeperWatcher(final ZooKeeperWatcher zkw) {
1754 if (zkw == null){
1755 return;
1756 }
1757 if (keepAliveZookeeperUserCount.addAndGet(-1) <= 0 ){
1758 keepZooKeeperWatcherAliveUntil = System.currentTimeMillis() + keepAlive;
1759 }
1760 }
1761
1762 private void closeZooKeeperWatcher() {
1763 synchronized (masterAndZKLock) {
1764 if (keepAliveZookeeper != null) {
1765 LOG.info("Closing zookeeper sessionid=0x" +
1766 Long.toHexString(
1767 keepAliveZookeeper.getRecoverableZooKeeper().getSessionId()));
1768 keepAliveZookeeper.internalClose();
1769 keepAliveZookeeper = null;
1770 }
1771 keepAliveZookeeperUserCount.set(0);
1772 }
1773 }
1774
1775 final MasterServiceState masterServiceState = new MasterServiceState(this);
1776
1777 @Override
1778 public MasterService.BlockingInterface getMaster() throws MasterNotRunningException {
1779 return getKeepAliveMasterService();
1780 }
1781
1782 private void resetMasterServiceState(final MasterServiceState mss) {
1783 mss.userCount++;
1784 }
1785
1786 @Override
1787 public MasterKeepAliveConnection getKeepAliveMasterService()
1788 throws MasterNotRunningException {
1789 synchronized (masterAndZKLock) {
1790 if (!isKeepAliveMasterConnectedAndRunning(this.masterServiceState)) {
1791 MasterServiceStubMaker stubMaker = new MasterServiceStubMaker();
1792 try {
1793 this.masterServiceState.stub = stubMaker.makeStub();
1794 } catch (MasterNotRunningException ex) {
1795 throw ex;
1796 } catch (IOException e) {
1797
1798 throw new MasterNotRunningException(e);
1799 }
1800 }
1801 resetMasterServiceState(this.masterServiceState);
1802 }
1803
1804 final MasterService.BlockingInterface stub = this.masterServiceState.stub;
1805 return new MasterKeepAliveConnection() {
1806 MasterServiceState mss = masterServiceState;
1807 @Override
1808 public MasterProtos.AbortProcedureResponse abortProcedure(
1809 RpcController controller,
1810 MasterProtos.AbortProcedureRequest request) throws ServiceException {
1811 return stub.abortProcedure(controller, request);
1812 }
1813 @Override
1814 public MasterProtos.ListProceduresResponse listProcedures(
1815 RpcController controller,
1816 MasterProtos.ListProceduresRequest request) throws ServiceException {
1817 return stub.listProcedures(controller, request);
1818 }
1819
1820 @Override
1821 public MasterProtos.ClearDeadServersResponse clearDeadServers(
1822 RpcController controller,
1823 MasterProtos.ClearDeadServersRequest request) throws ServiceException {
1824 return stub.clearDeadServers(controller, request);
1825 }
1826
1827 @Override
1828 public AddColumnResponse addColumn(RpcController controller, AddColumnRequest request)
1829 throws ServiceException {
1830 return stub.addColumn(controller, request);
1831 }
1832
1833 @Override
1834 public DeleteColumnResponse deleteColumn(RpcController controller,
1835 DeleteColumnRequest request)
1836 throws ServiceException {
1837 return stub.deleteColumn(controller, request);
1838 }
1839
1840 @Override
1841 public ModifyColumnResponse modifyColumn(RpcController controller,
1842 ModifyColumnRequest request)
1843 throws ServiceException {
1844 return stub.modifyColumn(controller, request);
1845 }
1846
1847 @Override
1848 public MoveRegionResponse moveRegion(RpcController controller,
1849 MoveRegionRequest request) throws ServiceException {
1850 return stub.moveRegion(controller, request);
1851 }
1852
1853 @Override
1854 public DispatchMergingRegionsResponse dispatchMergingRegions(
1855 RpcController controller, DispatchMergingRegionsRequest request)
1856 throws ServiceException {
1857 return stub.dispatchMergingRegions(controller, request);
1858 }
1859
1860 @Override
1861 public AssignRegionResponse assignRegion(RpcController controller,
1862 AssignRegionRequest request) throws ServiceException {
1863 return stub.assignRegion(controller, request);
1864 }
1865
1866 @Override
1867 public UnassignRegionResponse unassignRegion(RpcController controller,
1868 UnassignRegionRequest request) throws ServiceException {
1869 return stub.unassignRegion(controller, request);
1870 }
1871
1872 @Override
1873 public OfflineRegionResponse offlineRegion(RpcController controller,
1874 OfflineRegionRequest request) throws ServiceException {
1875 return stub.offlineRegion(controller, request);
1876 }
1877
1878 @Override
1879 public DeleteTableResponse deleteTable(RpcController controller,
1880 DeleteTableRequest request) throws ServiceException {
1881 return stub.deleteTable(controller, request);
1882 }
1883
1884 @Override
1885 public TruncateTableResponse truncateTable(RpcController controller,
1886 TruncateTableRequest request) throws ServiceException {
1887 return stub.truncateTable(controller, request);
1888 }
1889
1890 @Override
1891 public EnableTableResponse enableTable(RpcController controller,
1892 EnableTableRequest request) throws ServiceException {
1893 return stub.enableTable(controller, request);
1894 }
1895
1896 @Override
1897 public DisableTableResponse disableTable(RpcController controller,
1898 DisableTableRequest request) throws ServiceException {
1899 return stub.disableTable(controller, request);
1900 }
1901
1902 @Override
1903 public ModifyTableResponse modifyTable(RpcController controller,
1904 ModifyTableRequest request) throws ServiceException {
1905 return stub.modifyTable(controller, request);
1906 }
1907
1908 @Override
1909 public CreateTableResponse createTable(RpcController controller,
1910 CreateTableRequest request) throws ServiceException {
1911 return stub.createTable(controller, request);
1912 }
1913
1914 @Override
1915 public ShutdownResponse shutdown(RpcController controller,
1916 ShutdownRequest request) throws ServiceException {
1917 return stub.shutdown(controller, request);
1918 }
1919
1920 @Override
1921 public StopMasterResponse stopMaster(RpcController controller,
1922 StopMasterRequest request) throws ServiceException {
1923 return stub.stopMaster(controller, request);
1924 }
1925
1926 @Override
1927 public MasterProtos.IsInMaintenanceModeResponse isMasterInMaintenanceMode(
1928 final RpcController controller,
1929 final MasterProtos.IsInMaintenanceModeRequest request) throws ServiceException {
1930 return stub.isMasterInMaintenanceMode(controller, request);
1931 }
1932
1933 @Override
1934 public BalanceResponse balance(RpcController controller,
1935 BalanceRequest request) throws ServiceException {
1936 return stub.balance(controller, request);
1937 }
1938
1939 @Override
1940 public SetBalancerRunningResponse setBalancerRunning(
1941 RpcController controller, SetBalancerRunningRequest request)
1942 throws ServiceException {
1943 return stub.setBalancerRunning(controller, request);
1944 }
1945
1946 @Override
1947 public NormalizeResponse normalize(RpcController controller,
1948 NormalizeRequest request) throws ServiceException {
1949 return stub.normalize(controller, request);
1950 }
1951
1952 @Override
1953 public SetNormalizerRunningResponse setNormalizerRunning(
1954 RpcController controller, SetNormalizerRunningRequest request)
1955 throws ServiceException {
1956 return stub.setNormalizerRunning(controller, request);
1957 }
1958
1959 @Override
1960 public RunCatalogScanResponse runCatalogScan(RpcController controller,
1961 RunCatalogScanRequest request) throws ServiceException {
1962 return stub.runCatalogScan(controller, request);
1963 }
1964
1965 @Override
1966 public EnableCatalogJanitorResponse enableCatalogJanitor(
1967 RpcController controller, EnableCatalogJanitorRequest request)
1968 throws ServiceException {
1969 return stub.enableCatalogJanitor(controller, request);
1970 }
1971
1972 @Override
1973 public IsCatalogJanitorEnabledResponse isCatalogJanitorEnabled(
1974 RpcController controller, IsCatalogJanitorEnabledRequest request)
1975 throws ServiceException {
1976 return stub.isCatalogJanitorEnabled(controller, request);
1977 }
1978
1979 @Override
1980 public RunCleanerChoreResponse runCleanerChore(RpcController controller,
1981 RunCleanerChoreRequest request) throws ServiceException {
1982 return stub.runCleanerChore(controller, request);
1983 }
1984
1985 @Override
1986 public SetCleanerChoreRunningResponse setCleanerChoreRunning(RpcController controller,
1987 SetCleanerChoreRunningRequest request) throws ServiceException {
1988 return stub.setCleanerChoreRunning(controller, request);
1989 }
1990
1991 @Override
1992 public IsCleanerChoreEnabledResponse isCleanerChoreEnabled(
1993 RpcController controller, IsCleanerChoreEnabledRequest request)
1994 throws ServiceException {
1995 return stub.isCleanerChoreEnabled(controller, request);
1996 }
1997
1998 @Override
1999 public CoprocessorServiceResponse execMasterService(
2000 RpcController controller, CoprocessorServiceRequest request)
2001 throws ServiceException {
2002 return stub.execMasterService(controller, request);
2003 }
2004
2005 @Override
2006 public SnapshotResponse snapshot(RpcController controller,
2007 SnapshotRequest request) throws ServiceException {
2008 return stub.snapshot(controller, request);
2009 }
2010
2011 @Override
2012 public GetCompletedSnapshotsResponse getCompletedSnapshots(
2013 RpcController controller, GetCompletedSnapshotsRequest request)
2014 throws ServiceException {
2015 return stub.getCompletedSnapshots(controller, request);
2016 }
2017
2018 @Override
2019 public DeleteSnapshotResponse deleteSnapshot(RpcController controller,
2020 DeleteSnapshotRequest request) throws ServiceException {
2021 return stub.deleteSnapshot(controller, request);
2022 }
2023
2024 @Override
2025 public IsSnapshotDoneResponse isSnapshotDone(RpcController controller,
2026 IsSnapshotDoneRequest request) throws ServiceException {
2027 return stub.isSnapshotDone(controller, request);
2028 }
2029
2030 @Override
2031 public RestoreSnapshotResponse restoreSnapshot(
2032 RpcController controller, RestoreSnapshotRequest request)
2033 throws ServiceException {
2034 return stub.restoreSnapshot(controller, request);
2035 }
2036
2037 @Override
2038 public IsRestoreSnapshotDoneResponse isRestoreSnapshotDone(
2039 RpcController controller, IsRestoreSnapshotDoneRequest request)
2040 throws ServiceException {
2041 return stub.isRestoreSnapshotDone(controller, request);
2042 }
2043
2044 @Override
2045 public ExecProcedureResponse execProcedure(
2046 RpcController controller, ExecProcedureRequest request)
2047 throws ServiceException {
2048 return stub.execProcedure(controller, request);
2049 }
2050
2051 @Override
2052 public ExecProcedureResponse execProcedureWithRet(
2053 RpcController controller, ExecProcedureRequest request)
2054 throws ServiceException {
2055 return stub.execProcedureWithRet(controller, request);
2056 }
2057
2058 @Override
2059 public IsProcedureDoneResponse isProcedureDone(RpcController controller,
2060 IsProcedureDoneRequest request) throws ServiceException {
2061 return stub.isProcedureDone(controller, request);
2062 }
2063
2064 @Override
2065 public GetProcedureResultResponse getProcedureResult(RpcController controller,
2066 GetProcedureResultRequest request) throws ServiceException {
2067 return stub.getProcedureResult(controller, request);
2068 }
2069
2070 @Override
2071 public IsMasterRunningResponse isMasterRunning(
2072 RpcController controller, IsMasterRunningRequest request)
2073 throws ServiceException {
2074 return stub.isMasterRunning(controller, request);
2075 }
2076
2077 @Override
2078 public ModifyNamespaceResponse modifyNamespace(RpcController controller,
2079 ModifyNamespaceRequest request)
2080 throws ServiceException {
2081 return stub.modifyNamespace(controller, request);
2082 }
2083
2084 @Override
2085 public CreateNamespaceResponse createNamespace(
2086 RpcController controller, CreateNamespaceRequest request) throws ServiceException {
2087 return stub.createNamespace(controller, request);
2088 }
2089
2090 @Override
2091 public DeleteNamespaceResponse deleteNamespace(
2092 RpcController controller, DeleteNamespaceRequest request) throws ServiceException {
2093 return stub.deleteNamespace(controller, request);
2094 }
2095
2096 @Override
2097 public GetNamespaceDescriptorResponse getNamespaceDescriptor(RpcController controller,
2098 GetNamespaceDescriptorRequest request) throws ServiceException {
2099 return stub.getNamespaceDescriptor(controller, request);
2100 }
2101
2102 @Override
2103 public ListNamespaceDescriptorsResponse listNamespaceDescriptors(RpcController controller,
2104 ListNamespaceDescriptorsRequest request) throws ServiceException {
2105 return stub.listNamespaceDescriptors(controller, request);
2106 }
2107
2108 @Override
2109 public ListTableDescriptorsByNamespaceResponse listTableDescriptorsByNamespace(
2110 RpcController controller, ListTableDescriptorsByNamespaceRequest request)
2111 throws ServiceException {
2112 return stub.listTableDescriptorsByNamespace(controller, request);
2113 }
2114
2115 @Override
2116 public ListTableNamesByNamespaceResponse listTableNamesByNamespace(
2117 RpcController controller, ListTableNamesByNamespaceRequest request)
2118 throws ServiceException {
2119 return stub.listTableNamesByNamespace(controller, request);
2120 }
2121
2122 @Override
2123 public void close() {
2124 release(this.mss);
2125 }
2126
2127 @Override
2128 public GetSchemaAlterStatusResponse getSchemaAlterStatus(
2129 RpcController controller, GetSchemaAlterStatusRequest request)
2130 throws ServiceException {
2131 return stub.getSchemaAlterStatus(controller, request);
2132 }
2133
2134 @Override
2135 public GetTableDescriptorsResponse getTableDescriptors(
2136 RpcController controller, GetTableDescriptorsRequest request)
2137 throws ServiceException {
2138 return stub.getTableDescriptors(controller, request);
2139 }
2140
2141 @Override
2142 public GetTableNamesResponse getTableNames(
2143 RpcController controller, GetTableNamesRequest request)
2144 throws ServiceException {
2145 return stub.getTableNames(controller, request);
2146 }
2147
2148 @Override
2149 public GetClusterStatusResponse getClusterStatus(
2150 RpcController controller, GetClusterStatusRequest request)
2151 throws ServiceException {
2152 return stub.getClusterStatus(controller, request);
2153 }
2154
2155 @Override
2156 public SetQuotaResponse setQuota(RpcController controller, SetQuotaRequest request)
2157 throws ServiceException {
2158 return stub.setQuota(controller, request);
2159 }
2160
2161 @Override
2162 public MajorCompactionTimestampResponse getLastMajorCompactionTimestamp(
2163 RpcController controller, MajorCompactionTimestampRequest request)
2164 throws ServiceException {
2165 return stub.getLastMajorCompactionTimestamp(controller, request);
2166 }
2167
2168 @Override
2169 public MajorCompactionTimestampResponse getLastMajorCompactionTimestampForRegion(
2170 RpcController controller, MajorCompactionTimestampForRegionRequest request)
2171 throws ServiceException {
2172 return stub.getLastMajorCompactionTimestampForRegion(controller, request);
2173 }
2174
2175 @Override
2176 public IsBalancerEnabledResponse isBalancerEnabled(RpcController controller,
2177 IsBalancerEnabledRequest request) throws ServiceException {
2178 return stub.isBalancerEnabled(controller, request);
2179 }
2180
2181 @Override
2182 public MasterProtos.SetSplitOrMergeEnabledResponse setSplitOrMergeEnabled(
2183 RpcController controller,
2184 MasterProtos.SetSplitOrMergeEnabledRequest request) throws ServiceException {
2185 return stub.setSplitOrMergeEnabled(controller, request);
2186 }
2187
2188 @Override
2189 public MasterProtos.IsSplitOrMergeEnabledResponse isSplitOrMergeEnabled(
2190 RpcController controller,
2191 MasterProtos.IsSplitOrMergeEnabledRequest request) throws ServiceException {
2192 return stub.isSplitOrMergeEnabled(controller, request);
2193 }
2194
2195 @Override
2196 public IsNormalizerEnabledResponse isNormalizerEnabled(RpcController controller,
2197 IsNormalizerEnabledRequest request) throws ServiceException {
2198 return stub.isNormalizerEnabled(controller, request);
2199 }
2200
2201 @Override
2202 public SecurityCapabilitiesResponse getSecurityCapabilities(RpcController controller,
2203 SecurityCapabilitiesRequest request) throws ServiceException {
2204 return stub.getSecurityCapabilities(controller, request);
2205 }
2206 };
2207 }
2208
2209
2210 private static void release(MasterServiceState mss) {
2211 if (mss != null && mss.connection != null) {
2212 ((HConnectionImplementation)mss.connection).releaseMaster(mss);
2213 }
2214 }
2215
2216 private boolean isKeepAliveMasterConnectedAndRunning(MasterServiceState mss) {
2217 if (mss.getStub() == null){
2218 return false;
2219 }
2220 try {
2221 return mss.isMasterRunning();
2222 } catch (UndeclaredThrowableException e) {
2223
2224
2225 LOG.info("Master connection is not running anymore", e.getUndeclaredThrowable());
2226 return false;
2227 } catch (ServiceException se) {
2228 LOG.warn("Checking master connection", se);
2229 return false;
2230 }
2231 }
2232
2233 void releaseMaster(MasterServiceState mss) {
2234 if (mss.getStub() == null) return;
2235 synchronized (masterAndZKLock) {
2236 --mss.userCount;
2237 }
2238 }
2239
2240 private void closeMasterService(MasterServiceState mss) {
2241 if (mss.getStub() != null) {
2242 LOG.info("Closing master protocol: " + mss);
2243 mss.clearStub();
2244 }
2245 mss.userCount = 0;
2246 }
2247
2248
2249
2250
2251
2252 private void closeMaster() {
2253 synchronized (masterAndZKLock) {
2254 closeMasterService(masterServiceState);
2255 }
2256 }
2257
2258 void updateCachedLocation(HRegionInfo hri, ServerName source,
2259 ServerName serverName, long seqNum) {
2260 HRegionLocation newHrl = new HRegionLocation(hri, serverName, seqNum);
2261 cacheLocation(hri.getTable(), source, newHrl);
2262 }
2263
2264 @Override
2265 public void deleteCachedRegionLocation(final HRegionLocation location) {
2266 metaCache.clearCache(location);
2267 }
2268
2269 @Override
2270 public void updateCachedLocations(final TableName tableName, byte[] rowkey,
2271 final Object exception, final HRegionLocation source) {
2272 assert source != null;
2273 updateCachedLocations(tableName, source.getRegionInfo().getRegionName()
2274 , rowkey, exception, source.getServerName());
2275 }
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285 @Override
2286 public void updateCachedLocations(final TableName tableName, byte[] regionName, byte[] rowkey,
2287 final Object exception, final ServerName source) {
2288 if (rowkey == null || tableName == null) {
2289 LOG.warn("Coding error, see method javadoc. row=" + (rowkey == null ? "null" : rowkey) +
2290 ", tableName=" + (tableName == null ? "null" : tableName));
2291 return;
2292 }
2293
2294 if (source == null) {
2295
2296 return;
2297 }
2298
2299 if (regionName == null) {
2300
2301 if (metrics != null) {
2302 metrics.incrCacheDroppingExceptions(exception);
2303 }
2304 metaCache.clearCache(tableName, rowkey, source);
2305 return;
2306 }
2307
2308
2309 final RegionLocations oldLocations = getCachedLocation(tableName, rowkey);
2310 HRegionLocation oldLocation = null;
2311 if (oldLocations != null) {
2312 oldLocation = oldLocations.getRegionLocationByRegionName(regionName);
2313 }
2314 if (oldLocation == null || !source.equals(oldLocation.getServerName())) {
2315
2316
2317 return;
2318 }
2319
2320 HRegionInfo regionInfo = oldLocation.getRegionInfo();
2321 Throwable cause = ClientExceptionsUtil.findException(exception);
2322 if (cause != null) {
2323 if (!ClientExceptionsUtil.isMetaClearingException(cause)) {
2324
2325 return;
2326 }
2327
2328 if (cause instanceof RegionMovedException) {
2329 RegionMovedException rme = (RegionMovedException) cause;
2330 if (LOG.isTraceEnabled()) {
2331 LOG.trace("Region " + regionInfo.getRegionNameAsString() + " moved to " +
2332 rme.getHostname() + ":" + rme.getPort() +
2333 " according to " + source.getHostAndPort());
2334 }
2335
2336
2337 updateCachedLocation(
2338 regionInfo, source, rme.getServerName(), rme.getLocationSeqNum());
2339 return;
2340 }
2341 }
2342
2343 if (metrics != null) {
2344 metrics.incrCacheDroppingExceptions(exception);
2345 }
2346
2347
2348
2349 metaCache.clearCache(regionInfo);
2350 }
2351
2352 @Override
2353 public void updateCachedLocations(final byte[] tableName, byte[] rowkey,
2354 final Object exception, final HRegionLocation source) {
2355 updateCachedLocations(TableName.valueOf(tableName), rowkey, exception, source);
2356 }
2357
2358 @Override
2359 @Deprecated
2360 public void processBatch(List<? extends Row> list,
2361 final TableName tableName,
2362 ExecutorService pool,
2363 Object[] results) throws IOException, InterruptedException {
2364
2365
2366
2367 if (results.length != list.size()) {
2368 throw new IllegalArgumentException(
2369 "argument results must be the same size as argument list");
2370 }
2371 processBatchCallback(list, tableName, pool, results, null);
2372 }
2373
2374 @Override
2375 @Deprecated
2376 public void processBatch(List<? extends Row> list,
2377 final byte[] tableName,
2378 ExecutorService pool,
2379 Object[] results) throws IOException, InterruptedException {
2380 processBatch(list, TableName.valueOf(tableName), pool, results);
2381 }
2382
2383
2384
2385
2386
2387
2388
2389
2390 @Override
2391 @Deprecated
2392 public <R> void processBatchCallback(
2393 List<? extends Row> list,
2394 TableName tableName,
2395 ExecutorService pool,
2396 Object[] results,
2397 Batch.Callback<R> callback)
2398 throws IOException, InterruptedException {
2399
2400 AsyncRequestFuture ars = this.asyncProcess.submitAll(
2401 pool, tableName, list, callback, results);
2402 ars.waitUntilDone();
2403 if (ars.hasError()) {
2404 throw ars.getErrors();
2405 }
2406 }
2407
2408 @Override
2409 @Deprecated
2410 public <R> void processBatchCallback(
2411 List<? extends Row> list,
2412 byte[] tableName,
2413 ExecutorService pool,
2414 Object[] results,
2415 Batch.Callback<R> callback)
2416 throws IOException, InterruptedException {
2417 processBatchCallback(list, TableName.valueOf(tableName), pool, results, callback);
2418 }
2419
2420
2421 protected AsyncProcess createAsyncProcess(Configuration conf) {
2422
2423 return new AsyncProcess(this, conf, batchPool, rpcCallerFactory, false, rpcControllerFactory,
2424 writeRpcTimeout);
2425 }
2426
2427 @Override
2428 public AsyncProcess getAsyncProcess() {
2429 return asyncProcess;
2430 }
2431
2432 @Override
2433 public ServerStatisticTracker getStatisticsTracker() {
2434 return this.stats;
2435 }
2436
2437 @Override
2438 public ClientBackoffPolicy getBackoffPolicy() {
2439 return this.backoffPolicy;
2440 }
2441
2442
2443
2444
2445
2446 @VisibleForTesting
2447 int getNumberOfCachedRegionLocations(final TableName tableName) {
2448 return metaCache.getNumberOfCachedRegionLocations(tableName);
2449 }
2450
2451 @Override
2452 @Deprecated
2453 public void setRegionCachePrefetch(final TableName tableName, final boolean enable) {
2454 }
2455
2456 @Override
2457 @Deprecated
2458 public void setRegionCachePrefetch(final byte[] tableName,
2459 final boolean enable) {
2460 }
2461
2462 @Override
2463 @Deprecated
2464 public boolean getRegionCachePrefetch(TableName tableName) {
2465 return false;
2466 }
2467
2468 @Override
2469 @Deprecated
2470 public boolean getRegionCachePrefetch(byte[] tableName) {
2471 return false;
2472 }
2473
2474 @Override
2475 public void abort(final String msg, Throwable t) {
2476 if (t instanceof KeeperException.SessionExpiredException
2477 && keepAliveZookeeper != null) {
2478 synchronized (masterAndZKLock) {
2479 if (keepAliveZookeeper != null) {
2480 LOG.warn("This client just lost it's session with ZooKeeper," +
2481 " closing it." +
2482 " It will be recreated next time someone needs it", t);
2483 closeZooKeeperWatcher();
2484 }
2485 }
2486 } else {
2487 if (t != null) {
2488 LOG.fatal(msg, t);
2489 } else {
2490 LOG.fatal(msg);
2491 }
2492 this.aborted = true;
2493 close();
2494 this.closed = true;
2495 }
2496 }
2497
2498 @Override
2499 public boolean isClosed() {
2500 return this.closed;
2501 }
2502
2503 @Override
2504 public boolean isAborted(){
2505 return this.aborted;
2506 }
2507
2508 @Override
2509 public int getCurrentNrHRS() throws IOException {
2510 return this.registry.getCurrentNrHRS();
2511 }
2512
2513
2514
2515
2516 void incCount() {
2517 ++refCount;
2518 }
2519
2520
2521
2522
2523 void decCount() {
2524 if (refCount > 0) {
2525 --refCount;
2526 }
2527 }
2528
2529
2530
2531
2532
2533
2534 boolean isZeroReference() {
2535 return refCount == 0;
2536 }
2537
2538 void internalClose() {
2539 if (this.closed) {
2540 return;
2541 }
2542 closeMaster();
2543 shutdownPools();
2544 if (this.metrics != null) {
2545 this.metrics.shutdown();
2546 }
2547 this.closed = true;
2548 closeZooKeeperWatcher();
2549 this.stubs.clear();
2550 if (clusterStatusListener != null) {
2551 clusterStatusListener.close();
2552 }
2553 if (rpcClient != null) {
2554 rpcClient.close();
2555 }
2556 }
2557
2558 @Override
2559 public void close() {
2560 if (managed) {
2561 if (aborted) {
2562 ConnectionManager.deleteStaleConnection(this);
2563 } else {
2564 ConnectionManager.deleteConnection(this, false);
2565 }
2566 } else {
2567 internalClose();
2568 }
2569 }
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582 @Override
2583 protected void finalize() throws Throwable {
2584 super.finalize();
2585
2586 refCount = 1;
2587 close();
2588 }
2589
2590
2591
2592
2593 @Deprecated
2594 @Override
2595 public HTableDescriptor[] listTables() throws IOException {
2596 MasterKeepAliveConnection master = getKeepAliveMasterService();
2597 try {
2598 GetTableDescriptorsRequest req =
2599 RequestConverter.buildGetTableDescriptorsRequest((List<TableName>)null);
2600 return ProtobufUtil.getHTableDescriptorArray(master.getTableDescriptors(null, req));
2601 } catch (ServiceException se) {
2602 throw ProtobufUtil.getRemoteException(se);
2603 } finally {
2604 master.close();
2605 }
2606 }
2607
2608
2609
2610
2611 @Deprecated
2612 @Override
2613 public String[] getTableNames() throws IOException {
2614 TableName[] tableNames = listTableNames();
2615 String result[] = new String[tableNames.length];
2616 for (int i = 0; i < tableNames.length; i++) {
2617 result[i] = tableNames[i].getNameAsString();
2618 }
2619 return result;
2620 }
2621
2622
2623
2624
2625 @Deprecated
2626 @Override
2627 public TableName[] listTableNames() throws IOException {
2628 MasterKeepAliveConnection master = getKeepAliveMasterService();
2629 try {
2630 return ProtobufUtil.getTableNameArray(master.getTableNames(null,
2631 GetTableNamesRequest.newBuilder().build())
2632 .getTableNamesList());
2633 } catch (ServiceException se) {
2634 throw ProtobufUtil.getRemoteException(se);
2635 } finally {
2636 master.close();
2637 }
2638 }
2639
2640
2641
2642
2643 @Deprecated
2644 @Override
2645 public HTableDescriptor[] getHTableDescriptorsByTableName(
2646 List<TableName> tableNames) throws IOException {
2647 if (tableNames == null || tableNames.isEmpty()) return new HTableDescriptor[0];
2648 MasterKeepAliveConnection master = getKeepAliveMasterService();
2649 try {
2650 GetTableDescriptorsRequest req =
2651 RequestConverter.buildGetTableDescriptorsRequest(tableNames);
2652 return ProtobufUtil.getHTableDescriptorArray(master.getTableDescriptors(null, req));
2653 } catch (ServiceException se) {
2654 throw ProtobufUtil.getRemoteException(se);
2655 } finally {
2656 master.close();
2657 }
2658 }
2659
2660
2661
2662
2663 @Deprecated
2664 @Override
2665 public HTableDescriptor[] getHTableDescriptors(
2666 List<String> names) throws IOException {
2667 List<TableName> tableNames = new ArrayList<TableName>(names.size());
2668 for(String name : names) {
2669 tableNames.add(TableName.valueOf(name));
2670 }
2671
2672 return getHTableDescriptorsByTableName(tableNames);
2673 }
2674
2675 @Override
2676 public NonceGenerator getNonceGenerator() {
2677 return this.nonceGenerator;
2678 }
2679
2680
2681
2682
2683
2684
2685
2686
2687 @Deprecated
2688 @Override
2689 public HTableDescriptor getHTableDescriptor(final TableName tableName)
2690 throws IOException {
2691 if (tableName == null) return null;
2692 MasterKeepAliveConnection master = getKeepAliveMasterService();
2693 GetTableDescriptorsResponse htds;
2694 try {
2695 GetTableDescriptorsRequest req =
2696 RequestConverter.buildGetTableDescriptorsRequest(tableName);
2697 htds = master.getTableDescriptors(null, req);
2698 } catch (ServiceException se) {
2699 throw ProtobufUtil.getRemoteException(se);
2700 } finally {
2701 master.close();
2702 }
2703 if (!htds.getTableSchemaList().isEmpty()) {
2704 return HTableDescriptor.convert(htds.getTableSchemaList().get(0));
2705 }
2706 throw new TableNotFoundException(tableName.getNameAsString());
2707 }
2708
2709
2710
2711
2712 @Deprecated
2713 @Override
2714 public HTableDescriptor getHTableDescriptor(final byte[] tableName)
2715 throws IOException {
2716 return getHTableDescriptor(TableName.valueOf(tableName));
2717 }
2718
2719 @Override
2720 public RpcRetryingCallerFactory getNewRpcRetryingCallerFactory(Configuration conf) {
2721 return RpcRetryingCallerFactory
2722 .instantiate(conf, this.interceptor, this.getStatisticsTracker());
2723 }
2724
2725 @Override
2726 public boolean isManaged() {
2727 return managed;
2728 }
2729
2730 @Override
2731 public boolean hasCellBlockSupport() {
2732 return this.rpcClient.hasCellBlockSupport();
2733 }
2734
2735 @Override
2736 public ConnectionConfiguration getConnectionConfiguration() {
2737 return this.connectionConfig;
2738 }
2739
2740 @Override
2741 public RpcRetryingCallerFactory getRpcRetryingCallerFactory() {
2742 return this.rpcCallerFactory;
2743 }
2744
2745 @Override
2746 public RpcControllerFactory getRpcControllerFactory() {
2747 return this.rpcControllerFactory;
2748 }
2749 }
2750
2751
2752
2753
2754 static class ServerErrorTracker {
2755
2756 private final ConcurrentMap<ServerName, ServerErrors> errorsByServer =
2757 new ConcurrentHashMap<ServerName, ServerErrors>();
2758 private final long canRetryUntil;
2759 private final int maxRetries;
2760 private final long startTrackingTime;
2761
2762 public ServerErrorTracker(long timeout, int maxRetries) {
2763 this.maxRetries = maxRetries;
2764 this.canRetryUntil = EnvironmentEdgeManager.currentTime() + timeout;
2765 this.startTrackingTime = new Date().getTime();
2766 }
2767
2768
2769
2770
2771 boolean canRetryMore(int numRetry) {
2772
2773 return numRetry < maxRetries || (maxRetries > 1 &&
2774 EnvironmentEdgeManager.currentTime() < this.canRetryUntil);
2775 }
2776
2777
2778
2779
2780
2781
2782
2783
2784 long calculateBackoffTime(ServerName server, long basePause) {
2785 long result;
2786 ServerErrors errorStats = errorsByServer.get(server);
2787 if (errorStats != null) {
2788 result = ConnectionUtils.getPauseTime(basePause, errorStats.retries.get());
2789 } else {
2790 result = 0;
2791 }
2792 return result;
2793 }
2794
2795
2796
2797
2798
2799
2800 void reportServerError(ServerName server) {
2801 ServerErrors errors = errorsByServer.get(server);
2802 if (errors != null) {
2803 errors.addError();
2804 } else {
2805 errors = errorsByServer.putIfAbsent(server, new ServerErrors());
2806 if (errors != null){
2807 errors.addError();
2808 }
2809 }
2810 }
2811
2812 long getStartTrackingTime() {
2813 return startTrackingTime;
2814 }
2815
2816
2817
2818
2819 private static class ServerErrors {
2820 public final AtomicInteger retries = new AtomicInteger(0);
2821
2822 public void addError() {
2823 retries.incrementAndGet();
2824 }
2825 }
2826 }
2827 }