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