View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase;
20  
21  import java.io.IOException;
22  import java.security.PrivilegedExceptionAction;
23  import java.util.ArrayList;
24  import java.util.Collections;
25  import java.util.List;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.hbase.classification.InterfaceStability;
31  import org.apache.hadoop.conf.Configuration;
32  import org.apache.hadoop.hbase.client.Admin;
33  import org.apache.hadoop.hbase.client.Connection;
34  import org.apache.hadoop.hbase.client.ConnectionFactory;
35  import org.apache.hadoop.hbase.regionserver.HRegionServer;
36  import org.apache.hadoop.hbase.security.User;
37  import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
38  import org.apache.hadoop.hbase.util.Threads;
39  
40  import java.util.concurrent.CopyOnWriteArrayList;
41  import org.apache.hadoop.hbase.master.HMaster;
42  import org.apache.hadoop.hbase.util.JVMClusterUtil;
43  
44  /**
45   * This class creates a single process HBase cluster. One thread is created for
46   * a master and one per region server.
47   *
48   * Call {@link #startup()} to start the cluster running and {@link #shutdown()}
49   * to close it all down. {@link #join} the cluster is you want to wait on
50   * shutdown completion.
51   *
52   * <p>Runs master on port 16000 by default.  Because we can't just kill the
53   * process -- not till HADOOP-1700 gets fixed and even then.... -- we need to
54   * be able to find the master with a remote client to run shutdown.  To use a
55   * port other than 16000, set the hbase.master to a value of 'local:PORT':
56   * that is 'local', not 'localhost', and the port number the master should use
57   * instead of 16000.
58   *
59   */
60  @InterfaceAudience.Public
61  @InterfaceStability.Evolving
62  public class LocalHBaseCluster {
63    private static final Log LOG = LogFactory.getLog(LocalHBaseCluster.class);
64    private final List<JVMClusterUtil.MasterThread> masterThreads =
65      new CopyOnWriteArrayList<JVMClusterUtil.MasterThread>();
66    private final List<JVMClusterUtil.RegionServerThread> regionThreads =
67      new CopyOnWriteArrayList<JVMClusterUtil.RegionServerThread>();
68    private final static int DEFAULT_NO = 1;
69    /** local mode */
70    public static final String LOCAL = "local";
71    /** 'local:' */
72    public static final String LOCAL_COLON = LOCAL + ":";
73    private final Configuration conf;
74    private final Class<? extends HMaster> masterClass;
75    private final Class<? extends HRegionServer> regionServerClass;
76  
77    /**
78     * Constructor.
79     * @param conf
80     * @throws IOException
81     */
82    public LocalHBaseCluster(final Configuration conf)
83    throws IOException {
84      this(conf, DEFAULT_NO);
85    }
86  
87    /**
88     * Constructor.
89     * @param conf Configuration to use.  Post construction has the master's
90     * address.
91     * @param noRegionServers Count of regionservers to start.
92     * @throws IOException
93     */
94    public LocalHBaseCluster(final Configuration conf, final int noRegionServers)
95    throws IOException {
96      this(conf, 1, noRegionServers, getMasterImplementation(conf),
97          getRegionServerImplementation(conf));
98    }
99  
100   /**
101    * Constructor.
102    * @param conf Configuration to use.  Post construction has the active master
103    * address.
104    * @param noMasters Count of masters to start.
105    * @param noRegionServers Count of regionservers to start.
106    * @throws IOException
107    */
108   public LocalHBaseCluster(final Configuration conf, final int noMasters,
109       final int noRegionServers)
110   throws IOException {
111     this(conf, noMasters, noRegionServers, getMasterImplementation(conf),
112         getRegionServerImplementation(conf));
113   }
114 
115   @SuppressWarnings("unchecked")
116   private static Class<? extends HRegionServer> getRegionServerImplementation(final Configuration conf) {
117     return (Class<? extends HRegionServer>)conf.getClass(HConstants.REGION_SERVER_IMPL,
118        HRegionServer.class);
119   }
120 
121   @SuppressWarnings("unchecked")
122   private static Class<? extends HMaster> getMasterImplementation(final Configuration conf) {
123     return (Class<? extends HMaster>)conf.getClass(HConstants.MASTER_IMPL,
124        HMaster.class);
125   }
126 
127   /**
128    * Constructor.
129    * @param conf Configuration to use.  Post construction has the master's
130    * address.
131    * @param noMasters Count of masters to start.
132    * @param noRegionServers Count of regionservers to start.
133    * @param masterClass
134    * @param regionServerClass
135    * @throws IOException
136    */
137   @SuppressWarnings("unchecked")
138   public LocalHBaseCluster(final Configuration conf, final int noMasters,
139     final int noRegionServers, final Class<? extends HMaster> masterClass,
140     final Class<? extends HRegionServer> regionServerClass)
141   throws IOException {
142     this.conf = conf;
143 
144     // Always have masters and regionservers come up on port '0' so we don't
145     // clash over default ports.
146     conf.set(HConstants.MASTER_PORT, "0");
147     conf.set(HConstants.REGIONSERVER_PORT, "0");
148     if (conf.getInt(HConstants.REGIONSERVER_INFO_PORT, 0) != -1) {
149       conf.set(HConstants.REGIONSERVER_INFO_PORT, "0");
150     }
151 
152     this.masterClass = (Class<? extends HMaster>)
153       conf.getClass(HConstants.MASTER_IMPL, masterClass);
154     // Start the HMasters.
155     for (int i = 0; i < noMasters; i++) {
156       addMaster(new Configuration(conf), i);
157     }
158     // Start the HRegionServers.
159     this.regionServerClass =
160       (Class<? extends HRegionServer>)conf.getClass(HConstants.REGION_SERVER_IMPL,
161        regionServerClass);
162 
163     for (int i = 0; i < noRegionServers; i++) {
164       addRegionServer(new Configuration(conf), i);
165     }
166   }
167 
168   public JVMClusterUtil.RegionServerThread addRegionServer()
169       throws IOException {
170     return addRegionServer(new Configuration(conf), this.regionThreads.size());
171   }
172 
173   @SuppressWarnings("unchecked")
174   public JVMClusterUtil.RegionServerThread addRegionServer(
175       Configuration config, final int index)
176   throws IOException {
177     // Create each regionserver with its own Configuration instance so each has
178     // its HConnection instance rather than share (see HBASE_INSTANCES down in
179     // the guts of ConnectionManager).
180 
181     // Also, create separate CoordinatedStateManager instance per Server.
182     // This is special case when we have to have more than 1 CoordinatedStateManager
183     // within 1 process.
184     CoordinatedStateManager cp = CoordinatedStateManagerFactory.getCoordinatedStateManager(conf);
185 
186     JVMClusterUtil.RegionServerThread rst =
187         JVMClusterUtil.createRegionServerThread(config, cp, (Class<? extends HRegionServer>) conf
188             .getClass(HConstants.REGION_SERVER_IMPL, this.regionServerClass), index);
189 
190     this.regionThreads.add(rst);
191     return rst;
192   }
193 
194   public JVMClusterUtil.RegionServerThread addRegionServer(
195       final Configuration config, final int index, User user)
196   throws IOException, InterruptedException {
197     return user.runAs(
198         new PrivilegedExceptionAction<JVMClusterUtil.RegionServerThread>() {
199           public JVMClusterUtil.RegionServerThread run() throws Exception {
200             return addRegionServer(config, index);
201           }
202         });
203   }
204 
205   public JVMClusterUtil.MasterThread addMaster() throws IOException {
206     return addMaster(new Configuration(conf), this.masterThreads.size());
207   }
208 
209   public JVMClusterUtil.MasterThread addMaster(Configuration c, final int index)
210   throws IOException {
211     // Create each master with its own Configuration instance so each has
212     // its HConnection instance rather than share (see HBASE_INSTANCES down in
213     // the guts of ConnectionManager.
214 
215     // Also, create separate CoordinatedStateManager instance per Server.
216     // This is special case when we have to have more than 1 CoordinatedStateManager
217     // within 1 process.
218     CoordinatedStateManager cp = CoordinatedStateManagerFactory.getCoordinatedStateManager(conf);
219 
220     JVMClusterUtil.MasterThread mt = JVMClusterUtil.createMasterThread(c, cp,
221         (Class<? extends HMaster>) conf.getClass(HConstants.MASTER_IMPL, this.masterClass), index);
222     this.masterThreads.add(mt);
223     return mt;
224   }
225 
226   public JVMClusterUtil.MasterThread addMaster(
227       final Configuration c, final int index, User user)
228   throws IOException, InterruptedException {
229     return user.runAs(
230         new PrivilegedExceptionAction<JVMClusterUtil.MasterThread>() {
231           public JVMClusterUtil.MasterThread run() throws Exception {
232             return addMaster(c, index);
233           }
234         });
235   }
236 
237   /**
238    * @param serverNumber
239    * @return region server
240    */
241   public HRegionServer getRegionServer(int serverNumber) {
242     return regionThreads.get(serverNumber).getRegionServer();
243   }
244 
245   /**
246    * @return Read-only list of region server threads.
247    */
248   public List<JVMClusterUtil.RegionServerThread> getRegionServers() {
249     return Collections.unmodifiableList(this.regionThreads);
250   }
251 
252   /**
253    * @return List of running servers (Some servers may have been killed or
254    * aborted during lifetime of cluster; these servers are not included in this
255    * list).
256    */
257   public List<JVMClusterUtil.RegionServerThread> getLiveRegionServers() {
258     List<JVMClusterUtil.RegionServerThread> liveServers =
259       new ArrayList<JVMClusterUtil.RegionServerThread>();
260     List<RegionServerThread> list = getRegionServers();
261     for (JVMClusterUtil.RegionServerThread rst: list) {
262       if (rst.isAlive()) liveServers.add(rst);
263       else LOG.info("Not alive " + rst.getName());
264     }
265     return liveServers;
266   }
267 
268   /**
269    * @return the Configuration used by this LocalHBaseCluster
270    */
271   public Configuration getConfiguration() {
272     return this.conf;
273   }
274 
275   /**
276    * Wait for the specified region server to stop. Removes this thread from list of running threads.
277    * @return Name of region server that just went down.
278    */
279   public String waitOnRegionServer(int serverNumber) {
280     JVMClusterUtil.RegionServerThread regionServerThread = this.regionThreads.get(serverNumber);
281     return waitOnRegionServer(regionServerThread);
282   }
283 
284   /**
285    * Wait for the specified region server to stop. Removes this thread from list of running threads.
286    * @return Name of region server that just went down.
287    */
288   public String waitOnRegionServer(JVMClusterUtil.RegionServerThread rst) {
289     while (rst.isAlive()) {
290       try {
291         LOG.info("Waiting on " + rst.getRegionServer().toString());
292         rst.join();
293       } catch (InterruptedException e) {
294         e.printStackTrace();
295       }
296     }
297     regionThreads.remove(rst);
298     return rst.getName();
299   }
300 
301   /**
302    * @return the HMaster thread
303    */
304   public HMaster getMaster(int serverNumber) {
305     return masterThreads.get(serverNumber).getMaster();
306   }
307 
308   /**
309    * Gets the current active master, if available.  If no active master, returns
310    * null.
311    * @return the HMaster for the active master
312    */
313   public HMaster getActiveMaster() {
314     for (JVMClusterUtil.MasterThread mt : masterThreads) {
315       if (mt.getMaster().isActiveMaster()) {
316         // Ensure that the current active master is not stopped.
317         // We don't want to return a stopping master as an active master.
318         if (mt.getMaster().isActiveMaster()  && !mt.getMaster().isStopped()) {
319           return mt.getMaster();
320         }
321       }
322     }
323     return null;
324   }
325 
326   /**
327    * @return Read-only list of master threads.
328    */
329   public List<JVMClusterUtil.MasterThread> getMasters() {
330     return Collections.unmodifiableList(this.masterThreads);
331   }
332 
333   /**
334    * @return List of running master servers (Some servers may have been killed
335    * or aborted during lifetime of cluster; these servers are not included in
336    * this list).
337    */
338   public List<JVMClusterUtil.MasterThread> getLiveMasters() {
339     List<JVMClusterUtil.MasterThread> liveServers = new ArrayList<>();
340     List<JVMClusterUtil.MasterThread> list = getMasters();
341     for (JVMClusterUtil.MasterThread mt: list) {
342       if (mt.isAlive()) {
343         liveServers.add(mt);
344       }
345     }
346     return liveServers;
347   }
348 
349   /**
350    * Wait for the specified master to stop. Removes this thread from list of running threads.
351    * @return Name of master that just went down.
352    */
353   public String waitOnMaster(int serverNumber) {
354     JVMClusterUtil.MasterThread masterThread = this.masterThreads.get(serverNumber);
355     return waitOnMaster(masterThread);
356   }
357 
358   /**
359    * Wait for the specified master to stop. Removes this thread from list of running threads.
360    * @return Name of master that just went down.
361    */
362   public String waitOnMaster(JVMClusterUtil.MasterThread masterThread) {
363     while (masterThread.isAlive()) {
364       try {
365         LOG.info("Waiting on " + masterThread.getMaster().getServerName().toString());
366         masterThread.join();
367       } catch (InterruptedException e) {
368         e.printStackTrace();
369       }
370     }
371     masterThreads.remove(masterThread);
372     return masterThread.getName();
373   }
374 
375   /**
376    * Wait for Mini HBase Cluster to shut down.
377    * Presumes you've already called {@link #shutdown()}.
378    */
379   public void join() {
380     if (this.regionThreads != null) {
381       for(Thread t: this.regionThreads) {
382         if (t.isAlive()) {
383           try {
384             Threads.threadDumpingIsAlive(t);
385           } catch (InterruptedException e) {
386             LOG.debug("Interrupted", e);
387           }
388         }
389       }
390     }
391     if (this.masterThreads != null) {
392       for (Thread t : this.masterThreads) {
393         if (t.isAlive()) {
394           try {
395             Threads.threadDumpingIsAlive(t);
396           } catch (InterruptedException e) {
397             LOG.debug("Interrupted", e);
398           }
399         }
400       }
401     }
402   }
403 
404   /**
405    * Start the cluster.
406    */
407   public void startup() throws IOException {
408     JVMClusterUtil.startup(this.masterThreads, this.regionThreads);
409   }
410 
411   /**
412    * Shut down the mini HBase cluster
413    */
414   public void shutdown() {
415     JVMClusterUtil.shutdown(this.masterThreads, this.regionThreads);
416   }
417 
418   /**
419    * @param c Configuration to check.
420    * @return True if a 'local' address in hbase.master value.
421    */
422   public static boolean isLocal(final Configuration c) {
423     boolean mode = c.getBoolean(HConstants.CLUSTER_DISTRIBUTED, HConstants.DEFAULT_CLUSTER_DISTRIBUTED);
424     return(mode == HConstants.CLUSTER_IS_LOCAL);
425   }
426 
427   /**
428    * Test things basically work.
429    * @param args
430    * @throws IOException
431    */
432   public static void main(String[] args) throws IOException {
433     Configuration conf = HBaseConfiguration.create();
434     LocalHBaseCluster cluster = new LocalHBaseCluster(conf);
435     cluster.startup();
436     Connection connection = ConnectionFactory.createConnection(conf);
437     Admin admin = connection.getAdmin();
438     try {
439       HTableDescriptor htd =
440         new HTableDescriptor(TableName.valueOf(cluster.getClass().getName()));
441       admin.createTable(htd);
442     } finally {
443       admin.close();
444     }
445     connection.close();
446     cluster.shutdown();
447   }
448 }