001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.hadoop.hbase.rest;
020
021import java.lang.management.ManagementFactory;
022import java.util.ArrayList;
023import java.util.List;
024import java.util.Map;
025import java.util.EnumSet;
026import java.util.concurrent.ArrayBlockingQueue;
027
028import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
029import org.apache.commons.lang3.ArrayUtils;
030import org.apache.yetus.audience.InterfaceAudience;
031import org.apache.hadoop.conf.Configuration;
032import org.apache.hadoop.hbase.HBaseConfiguration;
033import org.apache.hadoop.hbase.HBaseInterfaceAudience;
034import org.apache.hadoop.hbase.http.InfoServer;
035import org.apache.hadoop.hbase.log.HBaseMarkers;
036import org.apache.hadoop.hbase.rest.filter.AuthFilter;
037import org.apache.hadoop.hbase.rest.filter.GzipFilter;
038import org.apache.hadoop.hbase.rest.filter.RestCsrfPreventionFilter;
039import org.apache.hadoop.hbase.security.UserProvider;
040import org.apache.hadoop.hbase.util.DNS;
041import org.apache.hadoop.hbase.http.HttpServerUtil;
042import org.apache.hadoop.hbase.util.Pair;
043import org.apache.hadoop.hbase.util.Strings;
044import org.apache.hadoop.hbase.util.VersionInfo;
045import org.apache.hadoop.util.StringUtils;
046
047import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
048import org.apache.hbase.thirdparty.org.apache.commons.cli.CommandLine;
049import org.apache.hbase.thirdparty.org.apache.commons.cli.HelpFormatter;
050import org.apache.hbase.thirdparty.org.apache.commons.cli.Options;
051import org.apache.hbase.thirdparty.org.apache.commons.cli.ParseException;
052import org.apache.hbase.thirdparty.org.apache.commons.cli.PosixParser;
053
054import org.eclipse.jetty.http.HttpVersion;
055import org.eclipse.jetty.server.Server;
056import org.eclipse.jetty.server.HttpConnectionFactory;
057import org.eclipse.jetty.server.SslConnectionFactory;
058import org.eclipse.jetty.server.HttpConfiguration;
059import org.eclipse.jetty.server.ServerConnector;
060import org.eclipse.jetty.server.SecureRequestCustomizer;
061import org.eclipse.jetty.util.ssl.SslContextFactory;
062import org.eclipse.jetty.servlet.ServletContextHandler;
063import org.eclipse.jetty.servlet.ServletHolder;
064import org.eclipse.jetty.util.thread.QueuedThreadPool;
065import org.eclipse.jetty.jmx.MBeanContainer;
066import org.eclipse.jetty.servlet.FilterHolder;
067
068import org.glassfish.jersey.server.ResourceConfig;
069import org.glassfish.jersey.servlet.ServletContainer;
070import org.slf4j.Logger;
071import org.slf4j.LoggerFactory;
072
073import javax.servlet.DispatcherType;
074
075/**
076 * Main class for launching REST gateway as a servlet hosted by Jetty.
077 * <p>
078 * The following options are supported:
079 * <ul>
080 * <li>-p --port : service port</li>
081 * <li>-ro --readonly : server mode</li>
082 * </ul>
083 */
084@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
085public class RESTServer implements Constants {
086  static Logger LOG = LoggerFactory.getLogger("RESTServer");
087
088  static String REST_CSRF_ENABLED_KEY = "hbase.rest.csrf.enabled";
089  static boolean REST_CSRF_ENABLED_DEFAULT = false;
090  static boolean restCSRFEnabled = false;
091  static String REST_CSRF_CUSTOM_HEADER_KEY ="hbase.rest.csrf.custom.header";
092  static String REST_CSRF_CUSTOM_HEADER_DEFAULT = "X-XSRF-HEADER";
093  static String REST_CSRF_METHODS_TO_IGNORE_KEY = "hbase.rest.csrf.methods.to.ignore";
094  static String REST_CSRF_METHODS_TO_IGNORE_DEFAULT = "GET,OPTIONS,HEAD,TRACE";
095
096  private static final String PATH_SPEC_ANY = "/*";
097
098  static String REST_HTTP_ALLOW_OPTIONS_METHOD = "hbase.rest.http.allow.options.method";
099  // HTTP OPTIONS method is commonly used in REST APIs for negotiation. It is disabled by default to
100  // maintain backward incompatibility
101  private static boolean REST_HTTP_ALLOW_OPTIONS_METHOD_DEFAULT = false;
102
103  private static void printUsageAndExit(Options options, int exitCode) {
104    HelpFormatter formatter = new HelpFormatter();
105    formatter.printHelp("hbase rest start", "", options,
106      "\nTo run the REST server as a daemon, execute " +
107      "hbase-daemon.sh start|stop rest [--infoport <port>] [-p <port>] [-ro]\n", true);
108    System.exit(exitCode);
109  }
110
111  /**
112   * Returns a list of strings from a comma-delimited configuration value.
113   *
114   * @param conf configuration to check
115   * @param name configuration property name
116   * @param defaultValue default value if no value found for name
117   * @return list of strings from comma-delimited configuration value, or an
118   *     empty list if not found
119   */
120  private static List<String> getTrimmedStringList(Configuration conf,
121    String name, String defaultValue) {
122    String valueString = conf.get(name, defaultValue);
123    if (valueString == null) {
124      return new ArrayList<>();
125    }
126    return new ArrayList<>(StringUtils.getTrimmedStringCollection(valueString));
127  }
128
129  static String REST_CSRF_BROWSER_USERAGENTS_REGEX_KEY = "hbase.rest-csrf.browser-useragents-regex";
130  static void addCSRFFilter(ServletContextHandler ctxHandler, Configuration conf) {
131    restCSRFEnabled = conf.getBoolean(REST_CSRF_ENABLED_KEY, REST_CSRF_ENABLED_DEFAULT);
132    if (restCSRFEnabled) {
133      Map<String, String> restCsrfParams = RestCsrfPreventionFilter
134          .getFilterParams(conf, "hbase.rest-csrf.");
135      FilterHolder holder = new FilterHolder();
136      holder.setName("csrf");
137      holder.setClassName(RestCsrfPreventionFilter.class.getName());
138      holder.setInitParameters(restCsrfParams);
139      ctxHandler.addFilter(holder, PATH_SPEC_ANY, EnumSet.allOf(DispatcherType.class));
140    }
141  }
142
143  // login the server principal (if using secure Hadoop)
144  private static Pair<FilterHolder, Class<? extends ServletContainer>> loginServerPrincipal(
145    UserProvider userProvider, Configuration conf) throws Exception {
146    Class<? extends ServletContainer> containerClass = ServletContainer.class;
147    if (userProvider.isHadoopSecurityEnabled() && userProvider.isHBaseSecurityEnabled()) {
148      String machineName = Strings.domainNamePointerToHostName(
149        DNS.getDefaultHost(conf.get(REST_DNS_INTERFACE, "default"),
150          conf.get(REST_DNS_NAMESERVER, "default")));
151      String keytabFilename = conf.get(REST_KEYTAB_FILE);
152      Preconditions.checkArgument(keytabFilename != null && !keytabFilename.isEmpty(),
153        REST_KEYTAB_FILE + " should be set if security is enabled");
154      String principalConfig = conf.get(REST_KERBEROS_PRINCIPAL);
155      Preconditions.checkArgument(principalConfig != null && !principalConfig.isEmpty(),
156        REST_KERBEROS_PRINCIPAL + " should be set if security is enabled");
157      userProvider.login(REST_KEYTAB_FILE, REST_KERBEROS_PRINCIPAL, machineName);
158      if (conf.get(REST_AUTHENTICATION_TYPE) != null) {
159        containerClass = RESTServletContainer.class;
160        FilterHolder authFilter = new FilterHolder();
161        authFilter.setClassName(AuthFilter.class.getName());
162        authFilter.setName("AuthenticationFilter");
163        return new Pair<>(authFilter,containerClass);
164      }
165    }
166    return new Pair<>(null, containerClass);
167  }
168
169  private static void parseCommandLine(String[] args, RESTServlet servlet) {
170    Options options = new Options();
171    options.addOption("p", "port", true, "Port to bind to [default: " + DEFAULT_LISTEN_PORT + "]");
172    options.addOption("ro", "readonly", false, "Respond only to GET HTTP " +
173      "method requests [default: false]");
174    options.addOption(null, "infoport", true, "Port for web UI");
175
176    CommandLine commandLine = null;
177    try {
178      commandLine = new PosixParser().parse(options, args);
179    } catch (ParseException e) {
180      LOG.error("Could not parse: ", e);
181      printUsageAndExit(options, -1);
182    }
183
184    // check for user-defined port setting, if so override the conf
185    if (commandLine != null && commandLine.hasOption("port")) {
186      String val = commandLine.getOptionValue("port");
187      servlet.getConfiguration().setInt("hbase.rest.port", Integer.parseInt(val));
188      if (LOG.isDebugEnabled()) {
189        LOG.debug("port set to " + val);
190      }
191    }
192
193    // check if server should only process GET requests, if so override the conf
194    if (commandLine != null && commandLine.hasOption("readonly")) {
195      servlet.getConfiguration().setBoolean("hbase.rest.readonly", true);
196      if (LOG.isDebugEnabled()) {
197        LOG.debug("readonly set to true");
198      }
199    }
200
201    // check for user-defined info server port setting, if so override the conf
202    if (commandLine != null && commandLine.hasOption("infoport")) {
203      String val = commandLine.getOptionValue("infoport");
204      servlet.getConfiguration().setInt("hbase.rest.info.port", Integer.parseInt(val));
205      if (LOG.isDebugEnabled()) {
206        LOG.debug("Web UI port set to " + val);
207      }
208    }
209
210    @SuppressWarnings("unchecked")
211    List<String> remainingArgs = commandLine != null ? commandLine.getArgList() : new ArrayList<>();
212    if (remainingArgs.size() != 1) {
213      printUsageAndExit(options, 1);
214    }
215
216    String command = remainingArgs.get(0);
217    if ("start".equals(command)) {
218      // continue and start container
219    } else if ("stop".equals(command)) {
220      System.exit(1);
221    } else {
222      printUsageAndExit(options, 1);
223    }
224  }
225
226  /**
227   * The main method for the HBase rest server.
228   * @param args command-line arguments
229   * @throws Exception exception
230   */
231  public static void main(String[] args) throws Exception {
232    LOG.info("***** STARTING service '" + RESTServer.class.getSimpleName() + "' *****");
233    VersionInfo.logVersion();
234    Configuration conf = HBaseConfiguration.create();
235    UserProvider userProvider = UserProvider.instantiate(conf);
236    Pair<FilterHolder, Class<? extends ServletContainer>> pair = loginServerPrincipal(
237      userProvider, conf);
238    FilterHolder authFilter = pair.getFirst();
239    RESTServlet servlet = RESTServlet.getInstance(conf, userProvider);
240
241    parseCommandLine(args, servlet);
242
243    // Set up the Jersey servlet container for Jetty
244    // The Jackson1Feature is a signal to Jersey that it should use jackson doing json.
245    // See here: https://stackoverflow.com/questions/39458230/how-register-jacksonfeature-on-clientconfig
246    ResourceConfig application = new ResourceConfig().
247        packages("org.apache.hadoop.hbase.rest").register(JacksonJaxbJsonProvider.class);
248    ServletHolder sh = new ServletHolder(new ServletContainer(application));
249
250    // Set the default max thread number to 100 to limit
251    // the number of concurrent requests so that REST server doesn't OOM easily.
252    // Jetty set the default max thread number to 250, if we don't set it.
253    //
254    // Our default min thread number 2 is the same as that used by Jetty.
255    int maxThreads = servlet.getConfiguration().getInt(REST_THREAD_POOL_THREADS_MAX, 100);
256    int minThreads = servlet.getConfiguration().getInt(REST_THREAD_POOL_THREADS_MIN, 2);
257    // Use the default queue (unbounded with Jetty 9.3) if the queue size is negative, otherwise use
258    // bounded {@link ArrayBlockingQueue} with the given size
259    int queueSize = servlet.getConfiguration().getInt(REST_THREAD_POOL_TASK_QUEUE_SIZE, -1);
260    int idleTimeout = servlet.getConfiguration().getInt(REST_THREAD_POOL_THREAD_IDLE_TIMEOUT, 60000);
261    QueuedThreadPool threadPool = queueSize > 0 ?
262        new QueuedThreadPool(maxThreads, minThreads, idleTimeout, new ArrayBlockingQueue<>(queueSize)) :
263        new QueuedThreadPool(maxThreads, minThreads, idleTimeout);
264
265    Server server = new Server(threadPool);
266
267    // Setup JMX
268    MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
269    server.addEventListener(mbContainer);
270    server.addBean(mbContainer);
271
272
273    String host = servlet.getConfiguration().get("hbase.rest.host", "0.0.0.0");
274    int servicePort = servlet.getConfiguration().getInt("hbase.rest.port", 8080);
275    HttpConfiguration httpConfig = new HttpConfiguration();
276    httpConfig.setSecureScheme("https");
277    httpConfig.setSecurePort(servicePort);
278    httpConfig.setSendServerVersion(false);
279    httpConfig.setSendDateHeader(false);
280
281    ServerConnector serverConnector;
282    if (conf.getBoolean(REST_SSL_ENABLED, false)) {
283      HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
284      httpsConfig.addCustomizer(new SecureRequestCustomizer());
285
286      SslContextFactory sslCtxFactory = new SslContextFactory();
287      String keystore = conf.get(REST_SSL_KEYSTORE_STORE);
288      String password = HBaseConfiguration.getPassword(conf,
289          REST_SSL_KEYSTORE_PASSWORD, null);
290      String keyPassword = HBaseConfiguration.getPassword(conf,
291          REST_SSL_KEYSTORE_KEYPASSWORD, password);
292      sslCtxFactory.setKeyStorePath(keystore);
293      sslCtxFactory.setKeyStorePassword(password);
294      sslCtxFactory.setKeyManagerPassword(keyPassword);
295
296      String[] excludeCiphers = servlet.getConfiguration().getStrings(
297          REST_SSL_EXCLUDE_CIPHER_SUITES, ArrayUtils.EMPTY_STRING_ARRAY);
298      if (excludeCiphers.length != 0) {
299        sslCtxFactory.setExcludeCipherSuites(excludeCiphers);
300      }
301      String[] includeCiphers = servlet.getConfiguration().getStrings(
302          REST_SSL_INCLUDE_CIPHER_SUITES, ArrayUtils.EMPTY_STRING_ARRAY);
303      if (includeCiphers.length != 0) {
304        sslCtxFactory.setIncludeCipherSuites(includeCiphers);
305      }
306
307      String[] excludeProtocols = servlet.getConfiguration().getStrings(
308          REST_SSL_EXCLUDE_PROTOCOLS, ArrayUtils.EMPTY_STRING_ARRAY);
309      if (excludeProtocols.length != 0) {
310        sslCtxFactory.setExcludeProtocols(excludeProtocols);
311      }
312      String[] includeProtocols = servlet.getConfiguration().getStrings(
313          REST_SSL_INCLUDE_PROTOCOLS, ArrayUtils.EMPTY_STRING_ARRAY);
314      if (includeProtocols.length != 0) {
315        sslCtxFactory.setIncludeProtocols(includeProtocols);
316      }
317
318      serverConnector = new ServerConnector(server,
319          new SslConnectionFactory(sslCtxFactory, HttpVersion.HTTP_1_1.toString()),
320          new HttpConnectionFactory(httpsConfig));
321    } else {
322      serverConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
323    }
324
325    int acceptQueueSize = servlet.getConfiguration().getInt(REST_CONNECTOR_ACCEPT_QUEUE_SIZE, -1);
326    if (acceptQueueSize >= 0) {
327      serverConnector.setAcceptQueueSize(acceptQueueSize);
328    }
329
330    serverConnector.setPort(servicePort);
331    serverConnector.setHost(host);
332
333    server.addConnector(serverConnector);
334    server.setStopAtShutdown(true);
335
336    // set up context
337    ServletContextHandler ctxHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
338    ctxHandler.addServlet(sh, PATH_SPEC_ANY);
339    if (authFilter != null) {
340      ctxHandler.addFilter(authFilter, PATH_SPEC_ANY, EnumSet.of(DispatcherType.REQUEST));
341    }
342
343    // Load filters from configuration.
344    String[] filterClasses = servlet.getConfiguration().getStrings(FILTER_CLASSES,
345        GzipFilter.class.getName());
346    for (String filter : filterClasses) {
347      filter = filter.trim();
348      ctxHandler.addFilter(filter, PATH_SPEC_ANY, EnumSet.of(DispatcherType.REQUEST));
349    }
350    addCSRFFilter(ctxHandler, conf);
351    HttpServerUtil.constrainHttpMethods(ctxHandler, servlet.getConfiguration()
352        .getBoolean(REST_HTTP_ALLOW_OPTIONS_METHOD, REST_HTTP_ALLOW_OPTIONS_METHOD_DEFAULT));
353
354    // Put up info server.
355    int port = conf.getInt("hbase.rest.info.port", 8085);
356    if (port >= 0) {
357      conf.setLong("startcode", System.currentTimeMillis());
358      String a = conf.get("hbase.rest.info.bindAddress", "0.0.0.0");
359      InfoServer infoServer = new InfoServer("rest", a, port, false, conf);
360      infoServer.setAttribute("hbase.conf", conf);
361      infoServer.start();
362    }
363    try {
364      // start server
365      server.start();
366      server.join();
367    } catch (Exception e) {
368      LOG.error(HBaseMarkers.FATAL, "Failed to start server", e);
369      System.exit(1);
370    }
371    LOG.info("***** STOPPING service '" + RESTServer.class.getSimpleName() + "' *****");
372  }
373}