001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase; 019 020import java.io.IOException; 021import java.security.PrivilegedAction; 022import java.util.ArrayList; 023import java.util.HashSet; 024import java.util.List; 025import java.util.Set; 026import org.apache.hadoop.conf.Configuration; 027import org.apache.hadoop.fs.FileSystem; 028import org.apache.hadoop.hbase.client.RegionReplicaUtil; 029import org.apache.hadoop.hbase.master.HMaster; 030import org.apache.hadoop.hbase.regionserver.HRegion; 031import org.apache.hadoop.hbase.regionserver.HRegion.FlushResult; 032import org.apache.hadoop.hbase.regionserver.HRegionServer; 033import org.apache.hadoop.hbase.regionserver.Region; 034import org.apache.hadoop.hbase.security.User; 035import org.apache.hadoop.hbase.test.MetricsAssertHelper; 036import org.apache.hadoop.hbase.util.JVMClusterUtil; 037import org.apache.hadoop.hbase.util.JVMClusterUtil.MasterThread; 038import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread; 039import org.apache.hadoop.hbase.util.Threads; 040import org.apache.yetus.audience.InterfaceAudience; 041import org.slf4j.Logger; 042import org.slf4j.LoggerFactory; 043 044import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.AdminService; 045import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.ClientService; 046import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MasterService; 047import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.RegionServerStartupResponse; 048 049/** 050 * This class creates a single process HBase cluster. each server. The master uses the 'default' 051 * FileSystem. The RegionServers, if we are running on DistributedFilesystem, create a FileSystem 052 * instance each and will close down their instance on the way out. 053 */ 054@InterfaceAudience.Public 055public class MiniHBaseCluster extends HBaseCluster { 056 private static final Logger LOG = LoggerFactory.getLogger(MiniHBaseCluster.class.getName()); 057 public LocalHBaseCluster hbaseCluster; 058 private static int index; 059 060 /** 061 * Start a MiniHBaseCluster. 062 * @param conf Configuration to be used for cluster 063 * @param numRegionServers initial number of region servers to start. 064 */ 065 public MiniHBaseCluster(Configuration conf, int numRegionServers) 066 throws IOException, InterruptedException { 067 this(conf, 1, numRegionServers); 068 } 069 070 /** 071 * Start a MiniHBaseCluster. 072 * @param conf Configuration to be used for cluster 073 * @param numMasters initial number of masters to start. 074 * @param numRegionServers initial number of region servers to start. 075 */ 076 public MiniHBaseCluster(Configuration conf, int numMasters, int numRegionServers) 077 throws IOException, InterruptedException { 078 this(conf, numMasters, numRegionServers, null, null); 079 } 080 081 /** 082 * Start a MiniHBaseCluster. 083 * @param conf Configuration to be used for cluster 084 * @param numMasters initial number of masters to start. 085 * @param numRegionServers initial number of region servers to start. 086 */ 087 public MiniHBaseCluster(Configuration conf, int numMasters, int numRegionServers, 088 Class<? extends HMaster> masterClass, 089 Class<? extends MiniHBaseCluster.MiniHBaseClusterRegionServer> regionserverClass) 090 throws IOException, InterruptedException { 091 this(conf, numMasters, 0, numRegionServers, null, masterClass, regionserverClass); 092 } 093 094 /** 095 * @param rsPorts Ports that RegionServer should use; pass ports if you want to test cluster 096 * restart where for sure the regionservers come up on same address+port (but just 097 * with different startcode); by default mini hbase clusters choose new arbitrary 098 * ports on each cluster start. 099 */ 100 public MiniHBaseCluster(Configuration conf, int numMasters, int numAlwaysStandByMasters, 101 int numRegionServers, List<Integer> rsPorts, Class<? extends HMaster> masterClass, 102 Class<? extends MiniHBaseCluster.MiniHBaseClusterRegionServer> regionserverClass) 103 throws IOException, InterruptedException { 104 super(conf); 105 106 // Hadoop 2 107 CompatibilityFactory.getInstance(MetricsAssertHelper.class).init(); 108 109 init(numMasters, numAlwaysStandByMasters, numRegionServers, rsPorts, masterClass, 110 regionserverClass); 111 this.initialClusterStatus = getClusterMetrics(); 112 } 113 114 public Configuration getConfiguration() { 115 return this.conf; 116 } 117 118 /** 119 * Subclass so can get at protected methods (none at moment). Also, creates a FileSystem instance 120 * per instantiation. Adds a shutdown own FileSystem on the way out. Shuts down own Filesystem 121 * only, not All filesystems as the FileSystem system exit hook does. 122 */ 123 public static class MiniHBaseClusterRegionServer extends HRegionServer { 124 private Thread shutdownThread = null; 125 private User user = null; 126 /** 127 * List of RegionServers killed so far. ServerName also comprises startCode of a server, so any 128 * restarted instances of the same server will have different ServerName and will not coincide 129 * with past dead ones. So there's no need to cleanup this list. 130 */ 131 static Set<ServerName> killedServers = new HashSet<>(); 132 133 public MiniHBaseClusterRegionServer(Configuration conf) 134 throws IOException, InterruptedException { 135 super(conf); 136 this.user = User.getCurrent(); 137 } 138 139 /* 140 * @param currentfs We return this if we did not make a new one. 141 * @param uniqueName Same name used to help identify the created fs. 142 * @return A new fs instance if we are up on DistributeFileSystem. 143 */ 144 145 @Override 146 protected void handleReportForDutyResponse(final RegionServerStartupResponse c) 147 throws IOException { 148 super.handleReportForDutyResponse(c); 149 // Run this thread to shutdown our filesystem on way out. 150 this.shutdownThread = new SingleFileSystemShutdownThread(getFileSystem()); 151 } 152 153 @Override 154 public void run() { 155 try { 156 this.user.runAs(new PrivilegedAction<Object>() { 157 @Override 158 public Object run() { 159 runRegionServer(); 160 return null; 161 } 162 }); 163 } catch (Throwable t) { 164 LOG.error("Exception in run", t); 165 } finally { 166 // Run this on the way out. 167 if (this.shutdownThread != null) { 168 this.shutdownThread.start(); 169 Threads.shutdown(this.shutdownThread, 30000); 170 } 171 } 172 } 173 174 private void runRegionServer() { 175 super.run(); 176 } 177 178 @Override 179 protected void kill() { 180 killedServers.add(getServerName()); 181 super.kill(); 182 } 183 184 @Override 185 public void abort(final String reason, final Throwable cause) { 186 this.user.runAs(new PrivilegedAction<Object>() { 187 @Override 188 public Object run() { 189 abortRegionServer(reason, cause); 190 return null; 191 } 192 }); 193 } 194 195 private void abortRegionServer(String reason, Throwable cause) { 196 super.abort(reason, cause); 197 } 198 } 199 200 /** 201 * Alternate shutdown hook. Just shuts down the passed fs, not all as default filesystem hook 202 * does. 203 */ 204 static class SingleFileSystemShutdownThread extends Thread { 205 private final FileSystem fs; 206 207 SingleFileSystemShutdownThread(final FileSystem fs) { 208 super("Shutdown of " + fs); 209 this.fs = fs; 210 } 211 212 @Override 213 public void run() { 214 try { 215 LOG.info("Hook closing fs=" + this.fs); 216 this.fs.close(); 217 } catch (IOException e) { 218 LOG.warn("Running hook", e); 219 } 220 } 221 } 222 223 private void init(final int nMasterNodes, final int numAlwaysStandByMasters, 224 final int nRegionNodes, List<Integer> rsPorts, Class<? extends HMaster> masterClass, 225 Class<? extends MiniHBaseCluster.MiniHBaseClusterRegionServer> regionserverClass) 226 throws IOException, InterruptedException { 227 try { 228 if (masterClass == null) { 229 masterClass = HMaster.class; 230 } 231 if (regionserverClass == null) { 232 regionserverClass = MiniHBaseCluster.MiniHBaseClusterRegionServer.class; 233 } 234 235 // start up a LocalHBaseCluster 236 hbaseCluster = new LocalHBaseCluster(conf, nMasterNodes, numAlwaysStandByMasters, 0, 237 masterClass, regionserverClass); 238 239 // manually add the regionservers as other users 240 for (int i = 0; i < nRegionNodes; i++) { 241 Configuration rsConf = HBaseConfiguration.create(conf); 242 if (rsPorts != null) { 243 rsConf.setInt(HConstants.REGIONSERVER_PORT, rsPorts.get(i)); 244 } 245 User user = HBaseTestingUtility.getDifferentUser(rsConf, ".hfs." + index++); 246 hbaseCluster.addRegionServer(rsConf, i, user); 247 } 248 249 hbaseCluster.startup(); 250 } catch (IOException e) { 251 shutdown(); 252 throw e; 253 } catch (Throwable t) { 254 LOG.error("Error starting cluster", t); 255 shutdown(); 256 throw new IOException("Shutting down", t); 257 } 258 } 259 260 @Override 261 public void startRegionServer(String hostname, int port) throws IOException { 262 final Configuration newConf = HBaseConfiguration.create(conf); 263 newConf.setInt(HConstants.REGIONSERVER_PORT, port); 264 startRegionServer(newConf); 265 } 266 267 @Override 268 public void killRegionServer(ServerName serverName) throws IOException { 269 HRegionServer server = getRegionServer(getRegionServerIndex(serverName)); 270 if (server instanceof MiniHBaseClusterRegionServer) { 271 LOG.info("Killing " + server.toString()); 272 ((MiniHBaseClusterRegionServer) server).kill(); 273 } else { 274 abortRegionServer(getRegionServerIndex(serverName)); 275 } 276 } 277 278 @Override 279 public boolean isKilledRS(ServerName serverName) { 280 return MiniHBaseClusterRegionServer.killedServers.contains(serverName); 281 } 282 283 @Override 284 public void stopRegionServer(ServerName serverName) throws IOException { 285 stopRegionServer(getRegionServerIndex(serverName)); 286 } 287 288 @Override 289 public void suspendRegionServer(ServerName serverName) throws IOException { 290 suspendRegionServer(getRegionServerIndex(serverName)); 291 } 292 293 @Override 294 public void resumeRegionServer(ServerName serverName) throws IOException { 295 resumeRegionServer(getRegionServerIndex(serverName)); 296 } 297 298 @Override 299 public void waitForRegionServerToStop(ServerName serverName, long timeout) throws IOException { 300 // ignore timeout for now 301 waitOnRegionServer(getRegionServerIndex(serverName)); 302 } 303 304 @Override 305 public void startZkNode(String hostname, int port) throws IOException { 306 LOG.warn("Starting zookeeper nodes on mini cluster is not supported"); 307 } 308 309 @Override 310 public void killZkNode(ServerName serverName) throws IOException { 311 LOG.warn("Aborting zookeeper nodes on mini cluster is not supported"); 312 } 313 314 @Override 315 public void stopZkNode(ServerName serverName) throws IOException { 316 LOG.warn("Stopping zookeeper nodes on mini cluster is not supported"); 317 } 318 319 @Override 320 public void waitForZkNodeToStart(ServerName serverName, long timeout) throws IOException { 321 LOG.warn("Waiting for zookeeper nodes to start on mini cluster is not supported"); 322 } 323 324 @Override 325 public void waitForZkNodeToStop(ServerName serverName, long timeout) throws IOException { 326 LOG.warn("Waiting for zookeeper nodes to stop on mini cluster is not supported"); 327 } 328 329 @Override 330 public void startDataNode(ServerName serverName) throws IOException { 331 LOG.warn("Starting datanodes on mini cluster is not supported"); 332 } 333 334 @Override 335 public void killDataNode(ServerName serverName) throws IOException { 336 LOG.warn("Aborting datanodes on mini cluster is not supported"); 337 } 338 339 @Override 340 public void stopDataNode(ServerName serverName) throws IOException { 341 LOG.warn("Stopping datanodes on mini cluster is not supported"); 342 } 343 344 @Override 345 public void waitForDataNodeToStart(ServerName serverName, long timeout) throws IOException { 346 LOG.warn("Waiting for datanodes to start on mini cluster is not supported"); 347 } 348 349 @Override 350 public void waitForDataNodeToStop(ServerName serverName, long timeout) throws IOException { 351 LOG.warn("Waiting for datanodes to stop on mini cluster is not supported"); 352 } 353 354 @Override 355 public void startNameNode(ServerName serverName) throws IOException { 356 LOG.warn("Starting namenodes on mini cluster is not supported"); 357 } 358 359 @Override 360 public void killNameNode(ServerName serverName) throws IOException { 361 LOG.warn("Aborting namenodes on mini cluster is not supported"); 362 } 363 364 @Override 365 public void stopNameNode(ServerName serverName) throws IOException { 366 LOG.warn("Stopping namenodes on mini cluster is not supported"); 367 } 368 369 @Override 370 public void waitForNameNodeToStart(ServerName serverName, long timeout) throws IOException { 371 LOG.warn("Waiting for namenodes to start on mini cluster is not supported"); 372 } 373 374 @Override 375 public void waitForNameNodeToStop(ServerName serverName, long timeout) throws IOException { 376 LOG.warn("Waiting for namenodes to stop on mini cluster is not supported"); 377 } 378 379 @Override 380 public void startMaster(String hostname, int port) throws IOException { 381 this.startMaster(); 382 } 383 384 @Override 385 public void killMaster(ServerName serverName) throws IOException { 386 abortMaster(getMasterIndex(serverName)); 387 } 388 389 @Override 390 public void stopMaster(ServerName serverName) throws IOException { 391 stopMaster(getMasterIndex(serverName)); 392 } 393 394 @Override 395 public void waitForMasterToStop(ServerName serverName, long timeout) throws IOException { 396 // ignore timeout for now 397 waitOnMaster(getMasterIndex(serverName)); 398 } 399 400 /** 401 * Starts a region server thread running 402 * @return New RegionServerThread 403 */ 404 public JVMClusterUtil.RegionServerThread startRegionServer() throws IOException { 405 final Configuration newConf = HBaseConfiguration.create(conf); 406 return startRegionServer(newConf); 407 } 408 409 private JVMClusterUtil.RegionServerThread startRegionServer(Configuration configuration) 410 throws IOException { 411 User rsUser = HBaseTestingUtility.getDifferentUser(configuration, ".hfs." + index++); 412 JVMClusterUtil.RegionServerThread t = null; 413 try { 414 t = 415 hbaseCluster.addRegionServer(configuration, hbaseCluster.getRegionServers().size(), rsUser); 416 t.start(); 417 t.waitForServerOnline(); 418 } catch (InterruptedException ie) { 419 throw new IOException("Interrupted adding regionserver to cluster", ie); 420 } 421 return t; 422 } 423 424 /** 425 * Starts a region server thread and waits until its processed by master. Throws an exception when 426 * it can't start a region server or when the region server is not processed by master within the 427 * timeout. 428 * @return New RegionServerThread 429 */ 430 public JVMClusterUtil.RegionServerThread startRegionServerAndWait(long timeout) 431 throws IOException { 432 433 JVMClusterUtil.RegionServerThread t = startRegionServer(); 434 ServerName rsServerName = t.getRegionServer().getServerName(); 435 436 long start = System.currentTimeMillis(); 437 ClusterStatus clusterStatus = getClusterStatus(); 438 while ((System.currentTimeMillis() - start) < timeout) { 439 if (clusterStatus != null && clusterStatus.getServers().contains(rsServerName)) { 440 return t; 441 } 442 Threads.sleep(100); 443 } 444 if (t.getRegionServer().isOnline()) { 445 throw new IOException("RS: " + rsServerName + " online, but not processed by master"); 446 } else { 447 throw new IOException("RS: " + rsServerName + " is offline"); 448 } 449 } 450 451 /** 452 * Cause a region server to exit doing basic clean up only on its way out. 453 * @param serverNumber Used as index into a list. 454 */ 455 public String abortRegionServer(int serverNumber) { 456 HRegionServer server = getRegionServer(serverNumber); 457 LOG.info("Aborting " + server.toString()); 458 server.abort("Aborting for tests", new Exception("Trace info")); 459 return server.toString(); 460 } 461 462 /** 463 * Shut down the specified region server cleanly 464 * @param serverNumber Used as index into a list. 465 * @return the region server that was stopped 466 */ 467 public JVMClusterUtil.RegionServerThread stopRegionServer(int serverNumber) { 468 return stopRegionServer(serverNumber, true); 469 } 470 471 /** 472 * Shut down the specified region server cleanly 473 * @param serverNumber Used as index into a list. 474 * @param shutdownFS True is we are to shutdown the filesystem as part of this regionserver's 475 * shutdown. Usually we do but you do not want to do this if you are running 476 * multiple regionservers in a test and you shut down one before end of the 477 * test. 478 * @return the region server that was stopped 479 */ 480 public JVMClusterUtil.RegionServerThread stopRegionServer(int serverNumber, 481 final boolean shutdownFS) { 482 JVMClusterUtil.RegionServerThread server = hbaseCluster.getRegionServers().get(serverNumber); 483 LOG.info("Stopping " + server.toString()); 484 server.getRegionServer().stop("Stopping rs " + serverNumber); 485 return server; 486 } 487 488 /** 489 * Suspend the specified region server 490 * @param serverNumber Used as index into a list. 491 */ 492 public JVMClusterUtil.RegionServerThread suspendRegionServer(int serverNumber) { 493 JVMClusterUtil.RegionServerThread server = hbaseCluster.getRegionServers().get(serverNumber); 494 LOG.info("Suspending {}", server.toString()); 495 server.suspend(); 496 return server; 497 } 498 499 /** 500 * Resume the specified region server 501 * @param serverNumber Used as index into a list. 502 */ 503 public JVMClusterUtil.RegionServerThread resumeRegionServer(int serverNumber) { 504 JVMClusterUtil.RegionServerThread server = hbaseCluster.getRegionServers().get(serverNumber); 505 LOG.info("Resuming {}", server.toString()); 506 server.resume(); 507 return server; 508 } 509 510 /** 511 * Wait for the specified region server to stop. Removes this thread from list of running threads. 512 * @return Name of region server that just went down. 513 */ 514 public String waitOnRegionServer(final int serverNumber) { 515 return this.hbaseCluster.waitOnRegionServer(serverNumber); 516 } 517 518 /** 519 * Starts a master thread running 520 * @return New RegionServerThread 521 */ 522 public JVMClusterUtil.MasterThread startMaster() throws IOException { 523 Configuration c = HBaseConfiguration.create(conf); 524 User user = HBaseTestingUtility.getDifferentUser(c, ".hfs." + index++); 525 526 JVMClusterUtil.MasterThread t = null; 527 try { 528 t = hbaseCluster.addMaster(c, hbaseCluster.getMasters().size(), user); 529 t.start(); 530 } catch (InterruptedException ie) { 531 throw new IOException("Interrupted adding master to cluster", ie); 532 } 533 conf.set(HConstants.MASTER_ADDRS_KEY, 534 hbaseCluster.getConfiguration().get(HConstants.MASTER_ADDRS_KEY)); 535 return t; 536 } 537 538 /** 539 * Returns the current active master, if available. 540 * @return the active HMaster, null if none is active. 541 */ 542 @Override 543 public MasterService.BlockingInterface getMasterAdminService() { 544 return this.hbaseCluster.getActiveMaster().getMasterRpcServices(); 545 } 546 547 /** 548 * Returns the current active master, if available. 549 * @return the active HMaster, null if none is active. 550 */ 551 public HMaster getMaster() { 552 return this.hbaseCluster.getActiveMaster(); 553 } 554 555 /** 556 * Returns the current active master thread, if available. 557 * @return the active MasterThread, null if none is active. 558 */ 559 public MasterThread getMasterThread() { 560 for (MasterThread mt : hbaseCluster.getLiveMasters()) { 561 if (mt.getMaster().isActiveMaster()) { 562 return mt; 563 } 564 } 565 return null; 566 } 567 568 /** 569 * Returns the master at the specified index, if available. 570 * @return the active HMaster, null if none is active. 571 */ 572 public HMaster getMaster(final int serverNumber) { 573 return this.hbaseCluster.getMaster(serverNumber); 574 } 575 576 /** 577 * Cause a master to exit without shutting down entire cluster. 578 * @param serverNumber Used as index into a list. 579 */ 580 public String abortMaster(int serverNumber) { 581 HMaster server = getMaster(serverNumber); 582 LOG.info("Aborting " + server.toString()); 583 server.abort("Aborting for tests", new Exception("Trace info")); 584 return server.toString(); 585 } 586 587 /** 588 * Shut down the specified master cleanly 589 * @param serverNumber Used as index into a list. 590 * @return the region server that was stopped 591 */ 592 public JVMClusterUtil.MasterThread stopMaster(int serverNumber) { 593 return stopMaster(serverNumber, true); 594 } 595 596 /** 597 * Shut down the specified master cleanly 598 * @param serverNumber Used as index into a list. 599 * @param shutdownFS True is we are to shutdown the filesystem as part of this master's 600 * shutdown. Usually we do but you do not want to do this if you are running 601 * multiple master in a test and you shut down one before end of the test. 602 * @return the master that was stopped 603 */ 604 public JVMClusterUtil.MasterThread stopMaster(int serverNumber, final boolean shutdownFS) { 605 JVMClusterUtil.MasterThread server = hbaseCluster.getMasters().get(serverNumber); 606 LOG.info("Stopping " + server.toString()); 607 server.getMaster().stop("Stopping master " + serverNumber); 608 return server; 609 } 610 611 /** 612 * Wait for the specified master to stop. Removes this thread from list of running threads. 613 * @return Name of master that just went down. 614 */ 615 public String waitOnMaster(final int serverNumber) { 616 return this.hbaseCluster.waitOnMaster(serverNumber); 617 } 618 619 /** 620 * Blocks until there is an active master and that master has completed initialization. 621 * @return true if an active master becomes available. false if there are no masters left. 622 */ 623 @Override 624 public boolean waitForActiveAndReadyMaster(long timeout) throws IOException { 625 List<JVMClusterUtil.MasterThread> mts; 626 long start = System.currentTimeMillis(); 627 while ( 628 !(mts = getMasterThreads()).isEmpty() && (System.currentTimeMillis() - start) < timeout 629 ) { 630 for (JVMClusterUtil.MasterThread mt : mts) { 631 if (mt.getMaster().isActiveMaster() && mt.getMaster().isInitialized()) { 632 return true; 633 } 634 } 635 636 Threads.sleep(100); 637 } 638 return false; 639 } 640 641 /** Returns List of master threads. */ 642 public List<JVMClusterUtil.MasterThread> getMasterThreads() { 643 return this.hbaseCluster.getMasters(); 644 } 645 646 /** Returns List of live master threads (skips the aborted and the killed) */ 647 public List<JVMClusterUtil.MasterThread> getLiveMasterThreads() { 648 return this.hbaseCluster.getLiveMasters(); 649 } 650 651 /** 652 * Wait for Mini HBase Cluster to shut down. 653 */ 654 public void join() { 655 this.hbaseCluster.join(); 656 } 657 658 /** 659 * Shut down the mini HBase cluster 660 */ 661 @Override 662 public void shutdown() throws IOException { 663 if (this.hbaseCluster != null) { 664 this.hbaseCluster.shutdown(); 665 } 666 } 667 668 @Override 669 public void close() throws IOException { 670 } 671 672 /** 673 * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0 Use 674 * {@link #getClusterMetrics()} instead. 675 */ 676 @Deprecated 677 public ClusterStatus getClusterStatus() throws IOException { 678 HMaster master = getMaster(); 679 return master == null ? null : new ClusterStatus(master.getClusterMetrics()); 680 } 681 682 @Override 683 public ClusterMetrics getClusterMetrics() throws IOException { 684 HMaster master = getMaster(); 685 return master == null ? null : master.getClusterMetrics(); 686 } 687 688 private void executeFlush(HRegion region) throws IOException { 689 if (!RegionReplicaUtil.isDefaultReplica(region.getRegionInfo())) { 690 return; 691 } 692 // retry 5 times if we can not flush 693 for (int i = 0; i < 5; i++) { 694 FlushResult result = region.flush(true); 695 if (result.getResult() != FlushResult.Result.CANNOT_FLUSH) { 696 return; 697 } 698 Threads.sleep(1000); 699 } 700 } 701 702 /** 703 * Call flushCache on all regions on all participating regionservers. 704 */ 705 public void flushcache() throws IOException { 706 for (JVMClusterUtil.RegionServerThread t : this.hbaseCluster.getRegionServers()) { 707 for (HRegion r : t.getRegionServer().getOnlineRegionsLocalContext()) { 708 executeFlush(r); 709 } 710 } 711 } 712 713 /** 714 * Call flushCache on all regions of the specified table. 715 */ 716 public void flushcache(TableName tableName) throws IOException { 717 for (JVMClusterUtil.RegionServerThread t : this.hbaseCluster.getRegionServers()) { 718 for (HRegion r : t.getRegionServer().getOnlineRegionsLocalContext()) { 719 if (r.getTableDescriptor().getTableName().equals(tableName)) { 720 executeFlush(r); 721 } 722 } 723 } 724 } 725 726 /** 727 * Call flushCache on all regions on all participating regionservers. 728 */ 729 public void compact(boolean major) throws IOException { 730 for (JVMClusterUtil.RegionServerThread t : this.hbaseCluster.getRegionServers()) { 731 for (HRegion r : t.getRegionServer().getOnlineRegionsLocalContext()) { 732 if (RegionReplicaUtil.isDefaultReplica(r.getRegionInfo())) { 733 r.compact(major); 734 } 735 } 736 } 737 } 738 739 /** 740 * Call flushCache on all regions of the specified table. 741 */ 742 public void compact(TableName tableName, boolean major) throws IOException { 743 for (JVMClusterUtil.RegionServerThread t : this.hbaseCluster.getRegionServers()) { 744 for (HRegion r : t.getRegionServer().getOnlineRegionsLocalContext()) { 745 if (r.getTableDescriptor().getTableName().equals(tableName)) { 746 if (RegionReplicaUtil.isDefaultReplica(r.getRegionInfo())) { 747 r.compact(major); 748 } 749 } 750 } 751 } 752 } 753 754 /** Returns Number of live region servers in the cluster currently. */ 755 public int getNumLiveRegionServers() { 756 return this.hbaseCluster.getLiveRegionServers().size(); 757 } 758 759 /** 760 * @return List of region server threads. Does not return the master even though it is also a 761 * region server. 762 */ 763 public List<JVMClusterUtil.RegionServerThread> getRegionServerThreads() { 764 return this.hbaseCluster.getRegionServers(); 765 } 766 767 /** Returns List of live region server threads (skips the aborted and the killed) */ 768 public List<JVMClusterUtil.RegionServerThread> getLiveRegionServerThreads() { 769 return this.hbaseCluster.getLiveRegionServers(); 770 } 771 772 /** 773 * Grab a numbered region server of your choice. 774 * @return region server 775 */ 776 public HRegionServer getRegionServer(int serverNumber) { 777 return hbaseCluster.getRegionServer(serverNumber); 778 } 779 780 public HRegionServer getRegionServer(ServerName serverName) { 781 return hbaseCluster.getRegionServers().stream().map(t -> t.getRegionServer()) 782 .filter(r -> r.getServerName().equals(serverName)).findFirst().orElse(null); 783 } 784 785 public List<HRegion> getRegions(byte[] tableName) { 786 return getRegions(TableName.valueOf(tableName)); 787 } 788 789 public List<HRegion> getRegions(TableName tableName) { 790 List<HRegion> ret = new ArrayList<>(); 791 for (JVMClusterUtil.RegionServerThread rst : getRegionServerThreads()) { 792 HRegionServer hrs = rst.getRegionServer(); 793 for (Region region : hrs.getOnlineRegionsLocalContext()) { 794 if (region.getTableDescriptor().getTableName().equals(tableName)) { 795 ret.add((HRegion) region); 796 } 797 } 798 } 799 return ret; 800 } 801 802 /** 803 * @return Index into List of {@link MiniHBaseCluster#getRegionServerThreads()} of HRS carrying 804 * regionName. Returns -1 if none found. 805 */ 806 public int getServerWithMeta() { 807 return getServerWith(HRegionInfo.FIRST_META_REGIONINFO.getRegionName()); 808 } 809 810 /** 811 * Get the location of the specified region 812 * @param regionName Name of the region in bytes 813 * @return Index into List of {@link MiniHBaseCluster#getRegionServerThreads()} of HRS carrying 814 * hbase:meta. Returns -1 if none found. 815 */ 816 public int getServerWith(byte[] regionName) { 817 int index = -1; 818 int count = 0; 819 for (JVMClusterUtil.RegionServerThread rst : getRegionServerThreads()) { 820 HRegionServer hrs = rst.getRegionServer(); 821 if (!hrs.isStopped()) { 822 Region region = hrs.getOnlineRegion(regionName); 823 if (region != null) { 824 index = count; 825 break; 826 } 827 } 828 count++; 829 } 830 return index; 831 } 832 833 @Override 834 public ServerName getServerHoldingRegion(final TableName tn, byte[] regionName) 835 throws IOException { 836 // Assume there is only one master thread which is the active master. 837 // If there are multiple master threads, the backup master threads 838 // should hold some regions. Please refer to #countServedRegions 839 // to see how we find out all regions. 840 HMaster master = getMaster(); 841 Region region = master.getOnlineRegion(regionName); 842 if (region != null) { 843 return master.getServerName(); 844 } 845 int index = getServerWith(regionName); 846 if (index < 0) { 847 return null; 848 } 849 return getRegionServer(index).getServerName(); 850 } 851 852 /** 853 * Counts the total numbers of regions being served by the currently online region servers by 854 * asking each how many regions they have. Does not look at hbase:meta at all. Count includes 855 * catalog tables. 856 * @return number of regions being served by all region servers 857 */ 858 public long countServedRegions() { 859 long count = 0; 860 for (JVMClusterUtil.RegionServerThread rst : getLiveRegionServerThreads()) { 861 count += rst.getRegionServer().getNumberOfOnlineRegions(); 862 } 863 for (JVMClusterUtil.MasterThread mt : getLiveMasterThreads()) { 864 count += mt.getMaster().getNumberOfOnlineRegions(); 865 } 866 return count; 867 } 868 869 /** 870 * Do a simulated kill all masters and regionservers. Useful when it is impossible to bring the 871 * mini-cluster back for clean shutdown. 872 */ 873 public void killAll() { 874 // Do backups first. 875 MasterThread activeMaster = null; 876 for (MasterThread masterThread : getMasterThreads()) { 877 if (!masterThread.getMaster().isActiveMaster()) { 878 masterThread.getMaster().abort("killAll"); 879 } else { 880 activeMaster = masterThread; 881 } 882 } 883 // Do active after. 884 if (activeMaster != null) { 885 activeMaster.getMaster().abort("killAll"); 886 } 887 for (RegionServerThread rst : getRegionServerThreads()) { 888 rst.getRegionServer().abort("killAll"); 889 } 890 } 891 892 @Override 893 public void waitUntilShutDown() { 894 this.hbaseCluster.join(); 895 } 896 897 public List<HRegion> findRegionsForTable(TableName tableName) { 898 ArrayList<HRegion> ret = new ArrayList<>(); 899 for (JVMClusterUtil.RegionServerThread rst : getRegionServerThreads()) { 900 HRegionServer hrs = rst.getRegionServer(); 901 for (Region region : hrs.getRegions(tableName)) { 902 if (region.getTableDescriptor().getTableName().equals(tableName)) { 903 ret.add((HRegion) region); 904 } 905 } 906 } 907 return ret; 908 } 909 910 protected int getRegionServerIndex(ServerName serverName) { 911 // we have a small number of region servers, this should be fine for now. 912 List<RegionServerThread> servers = getRegionServerThreads(); 913 for (int i = 0; i < servers.size(); i++) { 914 if (servers.get(i).getRegionServer().getServerName().equals(serverName)) { 915 return i; 916 } 917 } 918 return -1; 919 } 920 921 protected int getMasterIndex(ServerName serverName) { 922 List<MasterThread> masters = getMasterThreads(); 923 for (int i = 0; i < masters.size(); i++) { 924 if (masters.get(i).getMaster().getServerName().equals(serverName)) { 925 return i; 926 } 927 } 928 return -1; 929 } 930 931 @Override 932 public AdminService.BlockingInterface getAdminProtocol(ServerName serverName) throws IOException { 933 return getRegionServer(getRegionServerIndex(serverName)).getRSRpcServices(); 934 } 935 936 @Override 937 public ClientService.BlockingInterface getClientProtocol(ServerName serverName) 938 throws IOException { 939 return getRegionServer(getRegionServerIndex(serverName)).getRSRpcServices(); 940 } 941}