View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.thrift;
20  
21  import java.util.Arrays;
22  import java.util.List;
23  
24  import org.apache.commons.cli.CommandLine;
25  import org.apache.commons.cli.CommandLineParser;
26  import org.apache.commons.cli.HelpFormatter;
27  import org.apache.commons.cli.Options;
28  import org.apache.commons.cli.PosixParser;
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.classification.InterfaceAudience;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.hbase.HBaseConfiguration;
34  import org.apache.hadoop.hbase.http.InfoServer;
35  import org.apache.hadoop.hbase.security.UserProvider;
36  import org.apache.hadoop.hbase.thrift.ThriftServerRunner.ImplType;
37  import org.apache.hadoop.hbase.util.Strings;
38  import org.apache.hadoop.hbase.util.VersionInfo;
39  import org.apache.hadoop.net.DNS;
40  import org.apache.hadoop.util.Shell.ExitCodeException;
41  
42  /**
43   * ThriftServer- this class starts up a Thrift server which implements the
44   * Hbase API specified in the Hbase.thrift IDL file. The server runs in an
45   * independent process.
46   */
47  @InterfaceAudience.Private
48  public class ThriftServer {
49  
50    private static final Log LOG = LogFactory.getLog(ThriftServer.class);
51  
52    private static final String MIN_WORKERS_OPTION = "minWorkers";
53    private static final String MAX_WORKERS_OPTION = "workers";
54    private static final String MAX_QUEUE_SIZE_OPTION = "queue";
55    private static final String KEEP_ALIVE_SEC_OPTION = "keepAliveSec";
56    static final String BIND_OPTION = "bind";
57    static final String COMPACT_OPTION = "compact";
58    static final String FRAMED_OPTION = "framed";
59    static final String PORT_OPTION = "port";
60  
61    private static final String DEFAULT_BIND_ADDR = "0.0.0.0";
62    private static final int DEFAULT_LISTEN_PORT = 9090;
63  
64    private Configuration conf;
65    ThriftServerRunner serverRunner;
66  
67    private InfoServer infoServer;
68  
69    //
70    // Main program and support routines
71    //
72  
73    public ThriftServer(Configuration conf) {
74      this.conf = HBaseConfiguration.create(conf);
75    }
76  
77    private static void printUsageAndExit(Options options, int exitCode)
78        throws ExitCodeException {
79      HelpFormatter formatter = new HelpFormatter();
80      formatter.printHelp("Thrift", null, options,
81          "To start the Thrift server run 'bin/hbase-daemon.sh start thrift'\n" +
82          "To shutdown the thrift server run 'bin/hbase-daemon.sh stop " +
83          "thrift' or send a kill signal to the thrift server pid",
84          true);
85      throw new ExitCodeException(exitCode, "");
86    }
87  
88    /**
89     * Start up or shuts down the Thrift server, depending on the arguments.
90     * @param args
91     */
92     void doMain(final String[] args) throws Exception {
93       processOptions(args);
94  
95      UserProvider userProvider = UserProvider.instantiate(conf);
96      // login the server principal (if using secure Hadoop)
97      if (userProvider.isHadoopSecurityEnabled() && userProvider.isHBaseSecurityEnabled()) {
98        String machineName =
99            Strings.domainNamePointerToHostName(DNS.getDefaultHost(
100             conf.get("hbase.thrift.dns.interface", "default"),
101             conf.get("hbase.thrift.dns.nameserver", "default")));
102       userProvider
103           .login("hbase.thrift.keytab.file", "hbase.thrift.kerberos.principal", machineName);
104     }
105 
106      serverRunner = new ThriftServerRunner(conf);
107 
108      // Put up info server.
109      int port = conf.getInt("hbase.thrift.info.port", 9095);
110      if (port >= 0) {
111        conf.setLong("startcode", System.currentTimeMillis());
112        String a = conf.get("hbase.thrift.info.bindAddress", "0.0.0.0");
113        infoServer = new InfoServer("thrift", a, port, false, conf);
114        infoServer.setAttribute("hbase.conf", conf);
115        infoServer.start();
116      }
117      serverRunner.run();
118   }
119 
120   /**
121    * Parse the command line options to set parameters the conf.
122    */
123   private void processOptions(final String[] args) throws Exception {
124     Options options = new Options();
125     options.addOption("b", BIND_OPTION, true, "Address to bind " +
126         "the Thrift server to. [default: " + DEFAULT_BIND_ADDR + "]");
127     options.addOption("p", PORT_OPTION, true, "Port to bind to [default: " +
128         DEFAULT_LISTEN_PORT + "]");
129     options.addOption("f", FRAMED_OPTION, false, "Use framed transport");
130     options.addOption("c", COMPACT_OPTION, false, "Use the compact protocol");
131     options.addOption("h", "help", false, "Print help information");
132     options.addOption(null, "infoport", true, "Port for web UI");
133 
134     options.addOption("m", MIN_WORKERS_OPTION, true,
135         "The minimum number of worker threads for " +
136         ImplType.THREAD_POOL.simpleClassName());
137 
138     options.addOption("w", MAX_WORKERS_OPTION, true,
139         "The maximum number of worker threads for " +
140         ImplType.THREAD_POOL.simpleClassName());
141 
142     options.addOption("q", MAX_QUEUE_SIZE_OPTION, true,
143         "The maximum number of queued requests in " +
144         ImplType.THREAD_POOL.simpleClassName());
145 
146     options.addOption("k", KEEP_ALIVE_SEC_OPTION, true,
147         "The amount of time in secods to keep a thread alive when idle in " +
148         ImplType.THREAD_POOL.simpleClassName());
149 
150     options.addOptionGroup(ImplType.createOptionGroup());
151 
152     CommandLineParser parser = new PosixParser();
153     CommandLine cmd = parser.parse(options, args);
154 
155     // This is so complicated to please both bin/hbase and bin/hbase-daemon.
156     // hbase-daemon provides "start" and "stop" arguments
157     // hbase should print the help if no argument is provided
158     List<String> commandLine = Arrays.asList(args);
159     boolean stop = commandLine.contains("stop");
160     boolean start = commandLine.contains("start");
161     boolean invalidStartStop = (start && stop) || (!start && !stop);
162     if (cmd.hasOption("help") || invalidStartStop) {
163       if (invalidStartStop) {
164         LOG.error("Exactly one of 'start' and 'stop' has to be specified");
165       }
166       printUsageAndExit(options, 1);
167     }
168 
169     // Get port to bind to
170     try {
171       int listenPort = Integer.parseInt(cmd.getOptionValue(PORT_OPTION,
172           String.valueOf(DEFAULT_LISTEN_PORT)));
173       conf.setInt(ThriftServerRunner.PORT_CONF_KEY, listenPort);
174     } catch (NumberFormatException e) {
175       LOG.error("Could not parse the value provided for the port option", e);
176       printUsageAndExit(options, -1);
177     }
178 
179     // check for user-defined info server port setting, if so override the conf
180     try {
181       if (cmd.hasOption("infoport")) {
182         String val = cmd.getOptionValue("infoport");
183         conf.setInt("hbase.thrift.info.port", Integer.valueOf(val));
184         LOG.debug("Web UI port set to " + val);
185       }
186     } catch (NumberFormatException e) {
187       LOG.error("Could not parse the value provided for the infoport option", e);
188       printUsageAndExit(options, -1);
189     }
190 
191     // Make optional changes to the configuration based on command-line options
192     optionToConf(cmd, MIN_WORKERS_OPTION,
193         conf, TBoundedThreadPoolServer.MIN_WORKER_THREADS_CONF_KEY);
194     optionToConf(cmd, MAX_WORKERS_OPTION,
195         conf, TBoundedThreadPoolServer.MAX_WORKER_THREADS_CONF_KEY);
196     optionToConf(cmd, MAX_QUEUE_SIZE_OPTION,
197         conf, TBoundedThreadPoolServer.MAX_QUEUED_REQUESTS_CONF_KEY);
198     optionToConf(cmd, KEEP_ALIVE_SEC_OPTION,
199         conf, TBoundedThreadPoolServer.THREAD_KEEP_ALIVE_TIME_SEC_CONF_KEY);
200 
201     // Set general thrift server options
202     boolean compact = cmd.hasOption(COMPACT_OPTION) ||
203       conf.getBoolean(ThriftServerRunner.COMPACT_CONF_KEY, false);
204     conf.setBoolean(ThriftServerRunner.COMPACT_CONF_KEY, compact);
205     boolean framed = cmd.hasOption(FRAMED_OPTION) ||
206       conf.getBoolean(ThriftServerRunner.FRAMED_CONF_KEY, false);
207     conf.setBoolean(ThriftServerRunner.FRAMED_CONF_KEY, framed);
208     if (cmd.hasOption(BIND_OPTION)) {
209       conf.set(
210           ThriftServerRunner.BIND_CONF_KEY, cmd.getOptionValue(BIND_OPTION));
211     }
212 
213     ImplType.setServerImpl(cmd, conf);
214   }
215 
216   public void stop() {
217     if (this.infoServer != null) {
218       LOG.info("Stopping infoServer");
219       try {
220         this.infoServer.stop();
221       } catch (Exception ex) {
222         ex.printStackTrace();
223       }
224     }
225     serverRunner.shutdown();
226   }
227 
228   private static void optionToConf(CommandLine cmd, String option,
229       Configuration conf, String destConfKey) {
230     if (cmd.hasOption(option)) {
231       String value = cmd.getOptionValue(option);
232       LOG.info("Set configuration key:" + destConfKey + " value:" + value);
233       conf.set(destConfKey, value);
234     }
235   }
236 
237   /**
238    * @param args
239    * @throws Exception
240    */
241   public static void main(String [] args) throws Exception {
242     VersionInfo.logVersion();
243     try {
244       new ThriftServer(HBaseConfiguration.create()).doMain(args);
245     } catch (ExitCodeException ex) {
246       System.exit(ex.getExitCode());
247     }
248   }
249 }