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.rest;
20  
21  import java.util.ArrayList;
22  import java.util.List;
23  import java.util.Map;
24  import java.util.Map.Entry;
25  
26  import org.apache.commons.cli.CommandLine;
27  import org.apache.commons.cli.HelpFormatter;
28  import org.apache.commons.cli.Options;
29  import org.apache.commons.cli.ParseException;
30  import org.apache.commons.cli.PosixParser;
31  import org.apache.commons.lang.ArrayUtils;
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.classification.InterfaceAudience;
35  import org.apache.hadoop.conf.Configuration;
36  import org.apache.hadoop.hbase.HBaseConfiguration;
37  import org.apache.hadoop.hbase.http.InfoServer;
38  import org.apache.hadoop.hbase.rest.filter.AuthFilter;
39  import org.apache.hadoop.hbase.security.UserProvider;
40  import org.apache.hadoop.hbase.util.HttpServerUtil;
41  import org.apache.hadoop.hbase.util.Strings;
42  import org.apache.hadoop.hbase.util.VersionInfo;
43  import org.apache.hadoop.net.DNS;
44  import org.mortbay.jetty.Connector;
45  import org.mortbay.jetty.Server;
46  import org.mortbay.jetty.nio.SelectChannelConnector;
47  import org.mortbay.jetty.security.SslSelectChannelConnector;
48  import org.mortbay.jetty.servlet.Context;
49  import org.mortbay.jetty.servlet.FilterHolder;
50  import org.mortbay.jetty.servlet.ServletHolder;
51  import org.mortbay.thread.QueuedThreadPool;
52  
53  import com.google.common.base.Preconditions;
54  import com.sun.jersey.api.json.JSONConfiguration;
55  import com.sun.jersey.spi.container.servlet.ServletContainer;
56  
57  /**
58   * Main class for launching REST gateway as a servlet hosted by Jetty.
59   * <p>
60   * The following options are supported:
61   * <ul>
62   * <li>-p --port : service port</li>
63   * <li>-ro --readonly : server mode</li>
64   * </ul>
65   */
66  @InterfaceAudience.Private
67  public class RESTServer implements Constants {
68  
69    private static void printUsageAndExit(Options options, int exitCode) {
70      HelpFormatter formatter = new HelpFormatter();
71      formatter.printHelp("bin/hbase rest start", "", options,
72        "\nTo run the REST server as a daemon, execute " +
73        "bin/hbase-daemon.sh start|stop rest [--infoport <port>] [-p <port>] [-ro]\n", true);
74      System.exit(exitCode);
75    }
76  
77    /**
78     * The main method for the HBase rest server.
79     * @param args command-line arguments
80     * @throws Exception exception
81     */
82    public static void main(String[] args) throws Exception {
83      Log LOG = LogFactory.getLog("RESTServer");
84  
85      VersionInfo.logVersion();
86      FilterHolder authFilter = null;
87      Configuration conf = HBaseConfiguration.create();
88      Class<? extends ServletContainer> containerClass = ServletContainer.class;
89      UserProvider userProvider = UserProvider.instantiate(conf);
90      // login the server principal (if using secure Hadoop)
91      if (userProvider.isHadoopSecurityEnabled() && userProvider.isHBaseSecurityEnabled()) {
92        String machineName = Strings.domainNamePointerToHostName(
93          DNS.getDefaultHost(conf.get(REST_DNS_INTERFACE, "default"),
94            conf.get(REST_DNS_NAMESERVER, "default")));
95        String keytabFilename = conf.get(REST_KEYTAB_FILE);
96        Preconditions.checkArgument(keytabFilename != null && !keytabFilename.isEmpty(),
97          REST_KEYTAB_FILE + " should be set if security is enabled");
98        String principalConfig = conf.get(REST_KERBEROS_PRINCIPAL);
99        Preconditions.checkArgument(principalConfig != null && !principalConfig.isEmpty(),
100         REST_KERBEROS_PRINCIPAL + " should be set if security is enabled");
101       userProvider.login(REST_KEYTAB_FILE, REST_KERBEROS_PRINCIPAL, machineName);
102       if (conf.get(REST_AUTHENTICATION_TYPE) != null) {
103         containerClass = RESTServletContainer.class;
104         authFilter = new FilterHolder();
105         authFilter.setClassName(AuthFilter.class.getName());
106         authFilter.setName("AuthenticationFilter");
107       }
108     }
109 
110     RESTServlet servlet = RESTServlet.getInstance(conf, userProvider);
111 
112     Options options = new Options();
113     options.addOption("p", "port", true, "Port to bind to [default: 8080]");
114     options.addOption("ro", "readonly", false, "Respond only to GET HTTP " +
115       "method requests [default: false]");
116     options.addOption(null, "infoport", true, "Port for web UI");
117 
118     CommandLine commandLine = null;
119     try {
120       commandLine = new PosixParser().parse(options, args);
121     } catch (ParseException e) {
122       LOG.error("Could not parse: ", e);
123       printUsageAndExit(options, -1);
124     }
125 
126     // check for user-defined port setting, if so override the conf
127     if (commandLine != null && commandLine.hasOption("port")) {
128       String val = commandLine.getOptionValue("port");
129       servlet.getConfiguration()
130           .setInt("hbase.rest.port", Integer.valueOf(val));
131       LOG.debug("port set to " + val);
132     }
133 
134     // check if server should only process GET requests, if so override the conf
135     if (commandLine != null && commandLine.hasOption("readonly")) {
136       servlet.getConfiguration().setBoolean("hbase.rest.readonly", true);
137       LOG.debug("readonly set to true");
138     }
139 
140     // check for user-defined info server port setting, if so override the conf
141     if (commandLine != null && commandLine.hasOption("infoport")) {
142       String val = commandLine.getOptionValue("infoport");
143       servlet.getConfiguration()
144           .setInt("hbase.rest.info.port", Integer.valueOf(val));
145       LOG.debug("Web UI port set to " + val);
146     }
147 
148     @SuppressWarnings("unchecked")
149     List<String> remainingArgs = commandLine != null ?
150         commandLine.getArgList() : new ArrayList<String>();
151     if (remainingArgs.size() != 1) {
152       printUsageAndExit(options, 1);
153     }
154 
155     String command = remainingArgs.get(0);
156     if ("start".equals(command)) {
157       // continue and start container
158     } else if ("stop".equals(command)) {
159       System.exit(1);
160     } else {
161       printUsageAndExit(options, 1);
162     }
163 
164     // set up the Jersey servlet container for Jetty
165     ServletHolder sh = new ServletHolder(containerClass);
166     sh.setInitParameter(
167       "com.sun.jersey.config.property.resourceConfigClass",
168       ResourceConfig.class.getCanonicalName());
169     sh.setInitParameter("com.sun.jersey.config.property.packages",
170       "jetty");
171     // The servlet holder below is instantiated to only handle the case
172     // of the /status/cluster returning arrays of nodes (live/dead). Without
173     // this servlet holder, the problem is that the node arrays in the response
174     // are collapsed to single nodes. We want to be able to treat the
175     // node lists as POJO in the response to /status/cluster servlet call,
176     // but not change the behavior for any of the other servlets
177     // Hence we don't use the servlet holder for all servlets / paths
178     ServletHolder shPojoMap = new ServletHolder(containerClass);
179     @SuppressWarnings("unchecked")
180     Map<String, String> shInitMap = sh.getInitParameters();
181     for (Entry<String, String> e : shInitMap.entrySet()) {
182       shPojoMap.setInitParameter(e.getKey(), e.getValue());
183     }
184     shPojoMap.setInitParameter(JSONConfiguration.FEATURE_POJO_MAPPING, "true");
185 
186     // set up Jetty and run the embedded server
187 
188     Server server = new Server();
189 
190     Connector connector = new SelectChannelConnector();
191     if(conf.getBoolean(REST_SSL_ENABLED, false)) {
192       SslSelectChannelConnector sslConnector = new SslSelectChannelConnector();
193       String keystore = conf.get(REST_SSL_KEYSTORE_STORE);
194       String password = HBaseConfiguration.getPassword(conf,
195         REST_SSL_KEYSTORE_PASSWORD, null);
196       String keyPassword = HBaseConfiguration.getPassword(conf,
197         REST_SSL_KEYSTORE_KEYPASSWORD, password);
198       sslConnector.setKeystore(keystore);
199       sslConnector.setPassword(password);
200       sslConnector.setKeyPassword(keyPassword);
201       connector = sslConnector;
202     }
203     connector.setPort(servlet.getConfiguration().getInt("hbase.rest.port", 8080));
204     connector.setHost(servlet.getConfiguration().get("hbase.rest.host", "0.0.0.0"));
205 
206     server.addConnector(connector);
207 
208     // Set the default max thread number to 100 to limit
209     // the number of concurrent requests so that REST server doesn't OOM easily.
210     // Jetty set the default max thread number to 250, if we don't set it.
211     //
212     // Our default min thread number 2 is the same as that used by Jetty.
213     int maxThreads = servlet.getConfiguration().getInt("hbase.rest.threads.max", 100);
214     int minThreads = servlet.getConfiguration().getInt("hbase.rest.threads.min", 2);
215     QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads);
216     threadPool.setMinThreads(minThreads);
217     server.setThreadPool(threadPool);
218 
219     server.setSendServerVersion(false);
220     server.setSendDateHeader(false);
221     server.setStopAtShutdown(true);
222       // set up context
223     Context context = new Context(server, "/", Context.SESSIONS);
224     context.addServlet(shPojoMap, "/status/cluster");
225     context.addServlet(sh, "/*");
226     if (authFilter != null) {
227       context.addFilter(authFilter, "/*", 1);
228     }
229 
230     // Load filters from configuration.
231     String[] filterClasses = servlet.getConfiguration().getStrings(FILTER_CLASSES,
232       ArrayUtils.EMPTY_STRING_ARRAY);
233     for (String filter : filterClasses) {
234       filter = filter.trim();
235       context.addFilter(Class.forName(filter), "/*", 0);
236     }
237     HttpServerUtil.constrainHttpMethods(context);
238 
239     // Put up info server.
240     int port = conf.getInt("hbase.rest.info.port", 8085);
241     if (port >= 0) {
242       conf.setLong("startcode", System.currentTimeMillis());
243       String a = conf.get("hbase.rest.info.bindAddress", "0.0.0.0");
244       InfoServer infoServer = new InfoServer("rest", a, port, false, conf);
245       infoServer.setAttribute("hbase.conf", conf);
246       infoServer.start();
247     }
248 
249     // start server
250     server.start();
251     server.join();
252   }
253 }