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