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