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.master;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.util.List;
24  
25  import org.apache.commons.cli.CommandLine;
26  import org.apache.commons.cli.GnuParser;
27  import org.apache.commons.cli.Options;
28  import org.apache.commons.cli.ParseException;
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.conf.Configuration;
32  import org.apache.hadoop.hbase.CoordinatedStateManager;
33  import org.apache.hadoop.hbase.CoordinatedStateManagerFactory;
34  import org.apache.hadoop.hbase.HConstants;
35  import org.apache.hadoop.hbase.LocalHBaseCluster;
36  import org.apache.hadoop.hbase.MasterNotRunningException;
37  import org.apache.hadoop.hbase.ZNodeClearer;
38  import org.apache.hadoop.hbase.ZooKeeperConnectionException;
39  import org.apache.hadoop.hbase.classification.InterfaceAudience;
40  import org.apache.hadoop.hbase.client.Admin;
41  import org.apache.hadoop.hbase.client.Connection;
42  import org.apache.hadoop.hbase.client.ConnectionFactory;
43  import org.apache.hadoop.hbase.regionserver.HRegionServer;
44  import org.apache.hadoop.hbase.util.JVMClusterUtil;
45  import org.apache.hadoop.hbase.util.ServerCommandLine;
46  import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
47  import org.apache.hadoop.hbase.zookeeper.ZKUtil;
48  import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
49  import org.apache.zookeeper.KeeperException;
50  
51  @InterfaceAudience.Private
52  public class HMasterCommandLine extends ServerCommandLine {
53    private static final Log LOG = LogFactory.getLog(HMasterCommandLine.class);
54  
55    private static final String USAGE =
56      "Usage: Master [opts] start|stop|clear\n" +
57      " start  Start Master. If local mode, start Master and RegionServer in same JVM\n" +
58      " stop   Start cluster shutdown; Master signals RegionServer shutdown\n" +
59      " clear  Delete the master znode in ZooKeeper after a master crashes\n "+
60      " where [opts] are:\n" +
61      "   --minRegionServers=<servers>   Minimum RegionServers needed to host user tables.\n" +
62      "   --localRegionServers=<servers> " +
63        "RegionServers to start in master process when in standalone mode.\n" +
64      "   --masters=<servers>            Masters to start in this process.\n" +
65      "   --backup                       Master should start in backup mode";
66  
67    private final Class<? extends HMaster> masterClass;
68  
69    public HMasterCommandLine(Class<? extends HMaster> masterClass) {
70      this.masterClass = masterClass;
71    }
72  
73    protected String getUsage() {
74      return USAGE;
75    }
76  
77  
78    public int run(String args[]) throws Exception {
79      Options opt = new Options();
80      opt.addOption("localRegionServers", true,
81        "RegionServers to start in master process when running standalone");
82      opt.addOption("masters", true, "Masters to start in this process");
83      opt.addOption("minRegionServers", true, "Minimum RegionServers needed to host user tables");
84      opt.addOption("backup", false, "Do not try to become HMaster until the primary fails");
85  
86      CommandLine cmd;
87      try {
88        cmd = new GnuParser().parse(opt, args);
89      } catch (ParseException e) {
90        LOG.error("Could not parse: ", e);
91        usage(null);
92        return 1;
93      }
94  
95  
96      if (cmd.hasOption("minRegionServers")) {
97        String val = cmd.getOptionValue("minRegionServers");
98        getConf().setInt("hbase.regions.server.count.min",
99                    Integer.parseInt(val));
100       LOG.debug("minRegionServers set to " + val);
101     }
102 
103     // minRegionServers used to be minServers.  Support it too.
104     if (cmd.hasOption("minServers")) {
105       String val = cmd.getOptionValue("minServers");
106       getConf().setInt("hbase.regions.server.count.min", Integer.parseInt(val));
107       LOG.debug("minServers set to " + val);
108     }
109
110     // check if we are the backup master - override the conf if so
111     if (cmd.hasOption("backup")) {
112       getConf().setBoolean(HConstants.MASTER_TYPE_BACKUP, true);
113     }
114
115     // How many regionservers to startup in this process (we run regionservers in same process as
116     // master when we are in local/standalone mode. Useful testing)
117     if (cmd.hasOption("localRegionServers")) {
118       String val = cmd.getOptionValue("localRegionServers");
119       getConf().setInt("hbase.regionservers", Integer.parseInt(val));
120       LOG.debug("localRegionServers set to " + val);
121     }
122     // How many masters to startup inside this process; useful testing
123     if (cmd.hasOption("masters")) {
124       String val = cmd.getOptionValue("masters");
125       getConf().setInt("hbase.masters", Integer.parseInt(val));
126       LOG.debug("masters set to " + val);
127     }
128
129     @SuppressWarnings("unchecked")
130     List<String> remainingArgs = cmd.getArgList();
131     if (remainingArgs.size() != 1) {
132       usage(null);
133       return 1;
134     }
135
136     String command = remainingArgs.get(0);
137
138     if ("start".equals(command)) {
139       return startMaster();
140     } else if ("stop".equals(command)) {
141       return stopMaster();
142     } else if ("clear".equals(command)) {
143       return (ZNodeClearer.clear(getConf()) ? 0 : 1);
144     } else {
145       usage("Invalid command: " + command);
146       return 1;
147     }
148   }
149
150   private int startMaster() {
151     Configuration conf = getConf();
152     try {
153       // If 'local', defer to LocalHBaseCluster instance.  Starts master
154       // and regionserver both in the one JVM.
155       if (LocalHBaseCluster.isLocal(conf)) {
156         DefaultMetricsSystem.setMiniClusterMode(true);
157         final MiniZooKeeperCluster zooKeeperCluster = new MiniZooKeeperCluster(conf);
158         File zkDataPath = new File(conf.get(HConstants.ZOOKEEPER_DATA_DIR));
159
160         // find out the default client port
161         int zkClientPort = 0;
162
163         // If the zookeeper client port is specified in server quorum, use it.
164         String zkserver = conf.get(HConstants.ZOOKEEPER_QUORUM);
165         if (zkserver != null) {
166           String[] zkservers = zkserver.split(",");
167
168           if (zkservers.length > 1) {
169             // In local mode deployment, we have the master + a region server and zookeeper server
170             // started in the same process. Therefore, we only support one zookeeper server.
171             String errorMsg = "Could not start ZK with " + zkservers.length +
172                 " ZK servers in local mode deployment. Aborting as clients (e.g. shell) will not "
173                 + "be able to find this ZK quorum.";
174               System.err.println(errorMsg);
175               throw new IOException(errorMsg);
176           }
177
178           String[] parts = zkservers[0].split(":");
179
180           if (parts.length == 2) {
181             // the second part is the client port
182             zkClientPort = Integer.parseInt(parts [1]);
183           }
184         }
185         // If the client port could not be find in server quorum conf, try another conf
186         if (zkClientPort == 0) {
187           zkClientPort = conf.getInt(HConstants.ZOOKEEPER_CLIENT_PORT, 0);
188           // The client port has to be set by now; if not, throw exception.
189           if (zkClientPort == 0) {
190             throw new IOException("No config value for " + HConstants.ZOOKEEPER_CLIENT_PORT);
191           }
192         }
193         zooKeeperCluster.setDefaultClientPort(zkClientPort);
194         // set the ZK tick time if specified
195         int zkTickTime = conf.getInt(HConstants.ZOOKEEPER_TICK_TIME, 0);
196         if (zkTickTime > 0) {
197           zooKeeperCluster.setTickTime(zkTickTime);
198         }
199
200         // login the zookeeper server principal (if using security)
201         ZKUtil.loginServer(conf, HConstants.ZK_SERVER_KEYTAB_FILE,
202           HConstants.ZK_SERVER_KERBEROS_PRINCIPAL, null);
203         int localZKClusterSessionTimeout =
204           conf.getInt(HConstants.ZK_SESSION_TIMEOUT + ".localHBaseCluster", 10*1000);
205         conf.setInt(HConstants.ZK_SESSION_TIMEOUT, localZKClusterSessionTimeout);
206         LOG.info("Starting a zookeeper cluster");
207         int clientPort = zooKeeperCluster.startup(zkDataPath);
208         if (clientPort != zkClientPort) {
209           String errorMsg = "Could not start ZK at requested port of " +
210             zkClientPort + ".  ZK was started at port: " + clientPort +
211             ".  Aborting as clients (e.g. shell) will not be able to find " +
212             "this ZK quorum.";
213           System.err.println(errorMsg);
214           throw new IOException(errorMsg);
215         }
216         conf.set(HConstants.ZOOKEEPER_CLIENT_PORT, Integer.toString(clientPort));
217
218         // Need to have the zk cluster shutdown when master is shutdown.
219         // Run a subclass that does the zk cluster shutdown on its way out.
220         int mastersCount = conf.getInt("hbase.masters", 1);
221         int regionServersCount = conf.getInt("hbase.regionservers", 1);
222         // Set start timeout to 5 minutes for cmd line start operations
223         conf.setIfUnset("hbase.master.start.timeout.localHBaseCluster", "300000");
224         LOG.info("Starting up instance of localHBaseCluster; master=" + mastersCount +
225           ", regionserversCount=" + regionServersCount);
226         LocalHBaseCluster cluster = new LocalHBaseCluster(conf, mastersCount, regionServersCount,
227           LocalHMaster.class, HRegionServer.class);
228         ((LocalHMaster)cluster.getMaster(0)).setZKCluster(zooKeeperCluster);
229         cluster.startup();
230         waitOnMasterThreads(cluster);
231       } else {
232         logProcessInfo(getConf());
233         CoordinatedStateManager csm =
234           CoordinatedStateManagerFactory.getCoordinatedStateManager(conf);
235         HMaster master = HMaster.constructMaster(masterClass, conf, csm);
236         if (master.isStopped()) {
237           LOG.info("Won't bring the Master up as a shutdown is requested");
238           return 1;
239         }
240         master.start();
241         master.join();
242         if(master.isAborted())
243           throw new RuntimeException("HMaster Aborted");
244       }
245     } catch (Throwable t) {
246       LOG.error("Master exiting", t);
247       return 1;
248     }
249     return 0;
250   }
251
252   @SuppressWarnings("resource")
253   private int stopMaster() {
254     Configuration conf = getConf();
255     // Don't try more than once
256     conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 0);
257     try (Connection connection = ConnectionFactory.createConnection(conf)) {
258       try (Admin admin = connection.getAdmin()) {
259         admin.shutdown();
260       } catch (Throwable t) {
261         LOG.error("Failed to stop master", t);
262         return 1;
263       }
264     } catch (MasterNotRunningException e) {
265       LOG.error("Master not running");
266       return 1;
267     } catch (ZooKeeperConnectionException e) {
268       LOG.error("ZooKeeper not available");
269       return 1;
270     } catch (IOException e) {
271       LOG.error("Got IOException: " +e.getMessage(), e);
272       return 1;
273     }
274     return 0;
275   }
276
277   private void waitOnMasterThreads(LocalHBaseCluster cluster) throws InterruptedException{
278     List<JVMClusterUtil.MasterThread> masters = cluster.getMasters();
279     List<JVMClusterUtil.RegionServerThread> regionservers = cluster.getRegionServers();
280
281     if (masters != null) {
282       for (JVMClusterUtil.MasterThread t : masters) {
283         t.join();
284         if(t.getMaster().isAborted()) {
285           closeAllRegionServerThreads(regionservers);
286           throw new RuntimeException("HMaster Aborted");
287         }
288       }
289     }
290   }
291
292   private static void closeAllRegionServerThreads(
293       List<JVMClusterUtil.RegionServerThread> regionservers) {
294     for(JVMClusterUtil.RegionServerThread t : regionservers){
295       t.getRegionServer().stop("HMaster Aborted; Bringing down regions servers");
296     }
297   }
298
299   /*
300    * Version of master that will shutdown the passed zk cluster on its way out.
301    */
302   public static class LocalHMaster extends HMaster {
303     private MiniZooKeeperCluster zkcluster = null;
304
305     public LocalHMaster(Configuration conf, CoordinatedStateManager csm)
306     throws IOException, KeeperException, InterruptedException {
307       super(conf, csm);
308     }
309
310     @Override
311     public void run() {
312       super.run();
313       if (this.zkcluster != null) {
314         try {
315           this.zkcluster.shutdown();
316         } catch (IOException e) {
317           e.printStackTrace();
318         }
319       }
320     }
321
322     void setZKCluster(final MiniZooKeeperCluster zkcluster) {
323       this.zkcluster = zkcluster;
324     }
325   }
326 }