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.classification.InterfaceAudience;
30  import org.apache.hadoop.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     this.masterClass = (Class<? extends HMaster>)
147       conf.getClass(HConstants.MASTER_IMPL, masterClass);
148     // Start the HMasters.
149     for (int i = 0; i < noMasters; i++) {
150       addMaster(new Configuration(conf), i);
151     }
152     // Start the HRegionServers.
153     this.regionServerClass =
154       (Class<? extends HRegionServer>)conf.getClass(HConstants.REGION_SERVER_IMPL,
155        regionServerClass);
156 
157     for (int i = 0; i < noRegionServers; i++) {
158       addRegionServer(new Configuration(conf), i);
159     }
160   }
161 
162   public JVMClusterUtil.RegionServerThread addRegionServer()
163       throws IOException {
164     return addRegionServer(new Configuration(conf), this.regionThreads.size());
165   }
166 
167   public JVMClusterUtil.RegionServerThread addRegionServer(
168       Configuration config, final int index)
169   throws IOException {
170     // Create each regionserver with its own Configuration instance so each has
171     // its HConnection instance rather than share (see HBASE_INSTANCES down in
172     // the guts of HConnectionManager.
173     JVMClusterUtil.RegionServerThread rst =
174       JVMClusterUtil.createRegionServerThread(config,
175           this.regionServerClass, index);
176     this.regionThreads.add(rst);
177     return rst;
178   }
179 
180   public JVMClusterUtil.RegionServerThread addRegionServer(
181       final Configuration config, final int index, User user)
182   throws IOException, InterruptedException {
183     return user.runAs(
184         new PrivilegedExceptionAction<JVMClusterUtil.RegionServerThread>() {
185           public JVMClusterUtil.RegionServerThread run() throws Exception {
186             return addRegionServer(config, index);
187           }
188         });
189   }
190 
191   public JVMClusterUtil.MasterThread addMaster() throws IOException {
192     return addMaster(new Configuration(conf), this.masterThreads.size());
193   }
194 
195   public JVMClusterUtil.MasterThread addMaster(Configuration c, final int index)
196   throws IOException {
197     // Create each master with its own Configuration instance so each has
198     // its HConnection instance rather than share (see HBASE_INSTANCES down in
199     // the guts of HConnectionManager.
200     JVMClusterUtil.MasterThread mt = JVMClusterUtil.createMasterThread(c,
201         (Class<? extends HMaster>) conf.getClass(HConstants.MASTER_IMPL, this.masterClass), index);
202     this.masterThreads.add(mt);
203     return mt;
204   }
205 
206   public JVMClusterUtil.MasterThread addMaster(
207       final Configuration c, final int index, User user)
208   throws IOException, InterruptedException {
209     return user.runAs(
210         new PrivilegedExceptionAction<JVMClusterUtil.MasterThread>() {
211           public JVMClusterUtil.MasterThread run() throws Exception {
212             return addMaster(c, index);
213           }
214         });
215   }
216 
217   /**
218    * @param serverNumber
219    * @return region server
220    */
221   public HRegionServer getRegionServer(int serverNumber) {
222     return regionThreads.get(serverNumber).getRegionServer();
223   }
224 
225   /**
226    * @return Read-only list of region server threads.
227    */
228   public List<JVMClusterUtil.RegionServerThread> getRegionServers() {
229     return Collections.unmodifiableList(this.regionThreads);
230   }
231 
232   /**
233    * @return List of running servers (Some servers may have been killed or
234    * aborted during lifetime of cluster; these servers are not included in this
235    * list).
236    */
237   public List<JVMClusterUtil.RegionServerThread> getLiveRegionServers() {
238     List<JVMClusterUtil.RegionServerThread> liveServers =
239       new ArrayList<JVMClusterUtil.RegionServerThread>();
240     List<RegionServerThread> list = getRegionServers();
241     for (JVMClusterUtil.RegionServerThread rst: list) {
242       if (rst.isAlive()) liveServers.add(rst);
243       else LOG.info("Not alive " + rst.getName());
244     }
245     return liveServers;
246   }
247 
248   /**
249    * Wait for the specified region server to stop
250    * Removes this thread from list of running threads.
251    * @param serverNumber
252    * @return Name of region server that just went down.
253    */
254   public String waitOnRegionServer(int serverNumber) {
255     JVMClusterUtil.RegionServerThread regionServerThread =
256       this.regionThreads.remove(serverNumber);
257     while (regionServerThread.isAlive()) {
258       try {
259         LOG.info("Waiting on " +
260           regionServerThread.getRegionServer().toString());
261         regionServerThread.join();
262       } catch (InterruptedException e) {
263         e.printStackTrace();
264       }
265     }
266     return regionServerThread.getName();
267   }
268 
269   /**
270    * Wait for the specified region server to stop
271    * Removes this thread from list of running threads.
272    * @param rst
273    * @return Name of region server that just went down.
274    */
275   public String waitOnRegionServer(JVMClusterUtil.RegionServerThread rst) {
276     while (rst.isAlive()) {
277       try {
278         LOG.info("Waiting on " +
279           rst.getRegionServer().toString());
280         rst.join();
281       } catch (InterruptedException e) {
282         e.printStackTrace();
283       }
284     }
285     for (int i=0;i<regionThreads.size();i++) {
286       if (regionThreads.get(i) == rst) {
287         regionThreads.remove(i);
288         break;
289       }
290     }
291     return rst.getName();
292   }
293 
294   /**
295    * @param serverNumber
296    * @return the HMaster thread
297    */
298   public HMaster getMaster(int serverNumber) {
299     return masterThreads.get(serverNumber).getMaster();
300   }
301 
302   /**
303    * Gets the current active master, if available.  If no active master, returns
304    * null.
305    * @return the HMaster for the active master
306    */
307   public HMaster getActiveMaster() {
308     for (JVMClusterUtil.MasterThread mt : masterThreads) {
309       if (mt.getMaster().isActiveMaster()) {
310         // Ensure that the current active master is not stopped.
311         // We don't want to return a stopping master as an active master.
312         if (mt.getMaster().isActiveMaster()  && !mt.getMaster().isStopped()) {
313           return mt.getMaster();
314         }
315       }
316     }
317     return null;
318   }
319 
320   /**
321    * @return Read-only list of master threads.
322    */
323   public List<JVMClusterUtil.MasterThread> getMasters() {
324     return Collections.unmodifiableList(this.masterThreads);
325   }
326 
327   /**
328    * @return List of running master servers (Some servers may have been killed
329    * or aborted during lifetime of cluster; these servers are not included in
330    * this list).
331    */
332   public List<JVMClusterUtil.MasterThread> getLiveMasters() {
333     List<JVMClusterUtil.MasterThread> liveServers =
334       new ArrayList<JVMClusterUtil.MasterThread>();
335     List<JVMClusterUtil.MasterThread> list = getMasters();
336     for (JVMClusterUtil.MasterThread mt: list) {
337       if (mt.isAlive()) {
338         liveServers.add(mt);
339       }
340     }
341     return liveServers;
342   }
343 
344   /**
345    * Wait for the specified master to stop
346    * Removes this thread from list of running threads.
347    * @param serverNumber
348    * @return Name of master that just went down.
349    */
350   public String waitOnMaster(int serverNumber) {
351     JVMClusterUtil.MasterThread masterThread =
352       this.masterThreads.remove(serverNumber);
353     while (masterThread.isAlive()) {
354       try {
355         LOG.info("Waiting on " +
356           masterThread.getMaster().getServerName().toString());
357         masterThread.join();
358       } catch (InterruptedException e) {
359         e.printStackTrace();
360       }
361     }
362     return masterThread.getName();
363   }
364 
365   /**
366    * Wait for the specified master to stop
367    * Removes this thread from list of running threads.
368    * @param masterThread
369    * @return Name of master that just went down.
370    */
371   public String waitOnMaster(JVMClusterUtil.MasterThread masterThread) {
372     while (masterThread.isAlive()) {
373       try {
374         LOG.info("Waiting on " +
375           masterThread.getMaster().getServerName().toString());
376         masterThread.join();
377       } catch (InterruptedException e) {
378         e.printStackTrace();
379       }
380     }
381     for (int i=0;i<masterThreads.size();i++) {
382       if (masterThreads.get(i) == masterThread) {
383         masterThreads.remove(i);
384         break;
385       }
386     }
387     return masterThread.getName();
388   }
389 
390   /**
391    * Wait for Mini HBase Cluster to shut down.
392    * Presumes you've already called {@link #shutdown()}.
393    */
394   public void join() {
395     if (this.regionThreads != null) {
396       for(Thread t: this.regionThreads) {
397         if (t.isAlive()) {
398           try {
399             Threads.threadDumpingIsAlive(t);
400           } catch (InterruptedException e) {
401             LOG.debug("Interrupted", e);
402           }
403         }
404       }
405     }
406     if (this.masterThreads != null) {
407       for (Thread t : this.masterThreads) {
408         if (t.isAlive()) {
409           try {
410             Threads.threadDumpingIsAlive(t);
411           } catch (InterruptedException e) {
412             LOG.debug("Interrupted", e);
413           }
414         }
415       }
416     }
417   }
418 
419   /**
420    * Start the cluster.
421    */
422   public void startup() throws IOException {
423     JVMClusterUtil.startup(this.masterThreads, this.regionThreads);
424   }
425 
426   /**
427    * Shut down the mini HBase cluster
428    */
429   public void shutdown() {
430     JVMClusterUtil.shutdown(this.masterThreads, this.regionThreads);
431   }
432 
433   /**
434    * @param c Configuration to check.
435    * @return True if a 'local' address in hbase.master value.
436    */
437   public static boolean isLocal(final Configuration c) {
438     boolean mode = c.getBoolean(HConstants.CLUSTER_DISTRIBUTED, HConstants.DEFAULT_CLUSTER_DISTRIBUTED);
439     return(mode == HConstants.CLUSTER_IS_LOCAL);
440   }
441 
442   /**
443    * Test things basically work.
444    * @param args
445    * @throws IOException
446    */
447   public static void main(String[] args) throws IOException {
448     Configuration conf = HBaseConfiguration.create();
449     LocalHBaseCluster cluster = new LocalHBaseCluster(conf);
450     cluster.startup();
451     HBaseAdmin admin = new HBaseAdmin(conf);
452     HTableDescriptor htd =
453       new HTableDescriptor(TableName.valueOf(cluster.getClass().getName()));
454     admin.createTable(htd);
455     cluster.shutdown();
456   }
457 }