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