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