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