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