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.ReflectionUtils;
044import org.apache.hadoop.hbase.util.Strings;
045import org.apache.hadoop.hbase.util.VersionInfo;
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 final String REST_CSRF_ENABLED_KEY = "hbase.rest.csrf.enabled";
089  static final boolean REST_CSRF_ENABLED_DEFAULT = false;
090  boolean restCSRFEnabled = false;
091  static final String REST_CSRF_CUSTOM_HEADER_KEY ="hbase.rest.csrf.custom.header";
092  static final String REST_CSRF_CUSTOM_HEADER_DEFAULT = "X-XSRF-HEADER";
093  static final String REST_CSRF_METHODS_TO_IGNORE_KEY = "hbase.rest.csrf.methods.to.ignore";
094  static final String REST_CSRF_METHODS_TO_IGNORE_DEFAULT = "GET,OPTIONS,HEAD,TRACE";
095  public static final String SKIP_LOGIN_KEY = "hbase.rest.skip.login";
096
097  private static final String PATH_SPEC_ANY = "/*";
098
099  static final String REST_HTTP_ALLOW_OPTIONS_METHOD = "hbase.rest.http.allow.options.method";
100  // HTTP OPTIONS method is commonly used in REST APIs for negotiation. So it is enabled by default.
101  private static boolean REST_HTTP_ALLOW_OPTIONS_METHOD_DEFAULT = true;
102  static final String REST_CSRF_BROWSER_USERAGENTS_REGEX_KEY =
103    "hbase.rest-csrf.browser-useragents-regex";
104
105  // HACK, making this static for AuthFilter to get at our configuration. Necessary for unit tests.
106  @edu.umd.cs.findbugs.annotations.SuppressWarnings(
107    value={"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", "MS_CANNOT_BE_FINAL"},
108    justification="For testing")
109  public static Configuration conf = null;
110  private final UserProvider userProvider;
111  private Server server;
112  private InfoServer infoServer;
113
114  public RESTServer(Configuration conf) {
115    RESTServer.conf = conf;
116    this.userProvider = UserProvider.instantiate(conf);
117  }
118
119  private static void printUsageAndExit(Options options, int exitCode) {
120    HelpFormatter formatter = new HelpFormatter();
121    formatter.printHelp("hbase rest start", "", options,
122      "\nTo run the REST server as a daemon, execute " +
123      "hbase-daemon.sh start|stop rest [--infoport <port>] [-p <port>] [-ro]\n", true);
124    System.exit(exitCode);
125  }
126
127  void addCSRFFilter(ServletContextHandler ctxHandler, Configuration conf) {
128    restCSRFEnabled = conf.getBoolean(REST_CSRF_ENABLED_KEY, REST_CSRF_ENABLED_DEFAULT);
129    if (restCSRFEnabled) {
130      Map<String, String> restCsrfParams = RestCsrfPreventionFilter
131          .getFilterParams(conf, "hbase.rest-csrf.");
132      FilterHolder holder = new FilterHolder();
133      holder.setName("csrf");
134      holder.setClassName(RestCsrfPreventionFilter.class.getName());
135      holder.setInitParameters(restCsrfParams);
136      ctxHandler.addFilter(holder, PATH_SPEC_ANY, EnumSet.allOf(DispatcherType.class));
137    }
138  }
139
140  // login the server principal (if using secure Hadoop)
141  private static Pair<FilterHolder, Class<? extends ServletContainer>> loginServerPrincipal(
142    UserProvider userProvider, Configuration conf) throws Exception {
143    Class<? extends ServletContainer> containerClass = ServletContainer.class;
144    if (userProvider.isHadoopSecurityEnabled() && userProvider.isHBaseSecurityEnabled()) {
145      String machineName = Strings.domainNamePointerToHostName(
146        DNS.getDefaultHost(conf.get(REST_DNS_INTERFACE, "default"),
147          conf.get(REST_DNS_NAMESERVER, "default")));
148      String keytabFilename = conf.get(REST_KEYTAB_FILE);
149      Preconditions.checkArgument(keytabFilename != null && !keytabFilename.isEmpty(),
150        REST_KEYTAB_FILE + " should be set if security is enabled");
151      String principalConfig = conf.get(REST_KERBEROS_PRINCIPAL);
152      Preconditions.checkArgument(principalConfig != null && !principalConfig.isEmpty(),
153        REST_KERBEROS_PRINCIPAL + " should be set if security is enabled");
154      // Hook for unit tests, this will log out any other user and mess up tests.
155      if (!conf.getBoolean(SKIP_LOGIN_KEY, false)) {
156        userProvider.login(REST_KEYTAB_FILE, REST_KERBEROS_PRINCIPAL, machineName);
157      }
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, Configuration conf) {
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      conf.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      conf.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      conf.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    if (commandLine != null && commandLine.hasOption("skipLogin")) {
211      conf.setBoolean(SKIP_LOGIN_KEY, true);
212      if (LOG.isDebugEnabled()) {
213        LOG.debug("Skipping Kerberos login for REST server");
214      }
215    }
216
217    List<String> remainingArgs = commandLine != null ? commandLine.getArgList() : new ArrayList<>();
218    if (remainingArgs.size() != 1) {
219      printUsageAndExit(options, 1);
220    }
221
222    String command = remainingArgs.get(0);
223    if ("start".equals(command)) {
224      // continue and start container
225    } else if ("stop".equals(command)) {
226      System.exit(1);
227    } else {
228      printUsageAndExit(options, 1);
229    }
230  }
231
232
233  /**
234   * Runs the REST server.
235   */
236  public synchronized void run() throws Exception {
237    Pair<FilterHolder, Class<? extends ServletContainer>> pair = loginServerPrincipal(
238      userProvider, conf);
239    FilterHolder authFilter = pair.getFirst();
240    Class<? extends ServletContainer> containerClass = pair.getSecond();
241    RESTServlet servlet = RESTServlet.getInstance(conf, userProvider);
242
243    // set up the Jersey servlet container for Jetty
244    ResourceConfig application = new ResourceConfig().
245        packages("org.apache.hadoop.hbase.rest").register(JacksonJaxbJsonProvider.class);
246    // Using our custom ServletContainer is tremendously important. This is what makes sure the
247    // UGI.doAs() is done for the remoteUser, and calls are not made as the REST server itself.
248    ServletContainer servletContainer = ReflectionUtils.newInstance(containerClass, application);
249    ServletHolder sh = new ServletHolder(servletContainer);
250
251    // Set the default max thread number to 100 to limit
252    // the number of concurrent requests so that REST server doesn't OOM easily.
253    // Jetty set the default max thread number to 250, if we don't set it.
254    //
255    // Our default min thread number 2 is the same as that used by Jetty.
256    int maxThreads = servlet.getConfiguration().getInt(REST_THREAD_POOL_THREADS_MAX, 100);
257    int minThreads = servlet.getConfiguration().getInt(REST_THREAD_POOL_THREADS_MIN, 2);
258    // Use the default queue (unbounded with Jetty 9.3) if the queue size is negative, otherwise use
259    // bounded {@link ArrayBlockingQueue} with the given size
260    int queueSize = servlet.getConfiguration().getInt(REST_THREAD_POOL_TASK_QUEUE_SIZE, -1);
261    int idleTimeout = servlet.getConfiguration().getInt(REST_THREAD_POOL_THREAD_IDLE_TIMEOUT, 60000);
262    QueuedThreadPool threadPool = queueSize > 0 ?
263        new QueuedThreadPool(maxThreads, minThreads, idleTimeout, new ArrayBlockingQueue<>(queueSize)) :
264        new QueuedThreadPool(maxThreads, minThreads, idleTimeout);
265
266    this.server = new Server(threadPool);
267
268    // Setup JMX
269    MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
270    server.addEventListener(mbContainer);
271    server.addBean(mbContainer);
272
273
274    String host = servlet.getConfiguration().get("hbase.rest.host", "0.0.0.0");
275    int servicePort = servlet.getConfiguration().getInt("hbase.rest.port", 8080);
276    HttpConfiguration httpConfig = new HttpConfiguration();
277    httpConfig.setSecureScheme("https");
278    httpConfig.setSecurePort(servicePort);
279    httpConfig.setSendServerVersion(false);
280    httpConfig.setSendDateHeader(false);
281
282    ServerConnector serverConnector;
283    if (conf.getBoolean(REST_SSL_ENABLED, false)) {
284      HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
285      httpsConfig.addCustomizer(new SecureRequestCustomizer());
286
287      SslContextFactory sslCtxFactory = new SslContextFactory();
288      String keystore = conf.get(REST_SSL_KEYSTORE_STORE);
289      String password = HBaseConfiguration.getPassword(conf,
290          REST_SSL_KEYSTORE_PASSWORD, null);
291      String keyPassword = HBaseConfiguration.getPassword(conf,
292          REST_SSL_KEYSTORE_KEYPASSWORD, password);
293      sslCtxFactory.setKeyStorePath(keystore);
294      sslCtxFactory.setKeyStorePassword(password);
295      sslCtxFactory.setKeyManagerPassword(keyPassword);
296
297      String[] excludeCiphers = servlet.getConfiguration().getStrings(
298          REST_SSL_EXCLUDE_CIPHER_SUITES, ArrayUtils.EMPTY_STRING_ARRAY);
299      if (excludeCiphers.length != 0) {
300        sslCtxFactory.setExcludeCipherSuites(excludeCiphers);
301      }
302      String[] includeCiphers = servlet.getConfiguration().getStrings(
303          REST_SSL_INCLUDE_CIPHER_SUITES, ArrayUtils.EMPTY_STRING_ARRAY);
304      if (includeCiphers.length != 0) {
305        sslCtxFactory.setIncludeCipherSuites(includeCiphers);
306      }
307
308      String[] excludeProtocols = servlet.getConfiguration().getStrings(
309          REST_SSL_EXCLUDE_PROTOCOLS, ArrayUtils.EMPTY_STRING_ARRAY);
310      if (excludeProtocols.length != 0) {
311        sslCtxFactory.setExcludeProtocols(excludeProtocols);
312      }
313      String[] includeProtocols = servlet.getConfiguration().getStrings(
314          REST_SSL_INCLUDE_PROTOCOLS, ArrayUtils.EMPTY_STRING_ARRAY);
315      if (includeProtocols.length != 0) {
316        sslCtxFactory.setIncludeProtocols(includeProtocols);
317      }
318
319      serverConnector = new ServerConnector(server,
320          new SslConnectionFactory(sslCtxFactory, HttpVersion.HTTP_1_1.toString()),
321          new HttpConnectionFactory(httpsConfig));
322    } else {
323      serverConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
324    }
325
326    int acceptQueueSize = servlet.getConfiguration().getInt(REST_CONNECTOR_ACCEPT_QUEUE_SIZE, -1);
327    if (acceptQueueSize >= 0) {
328      serverConnector.setAcceptQueueSize(acceptQueueSize);
329    }
330
331    serverConnector.setPort(servicePort);
332    serverConnector.setHost(host);
333
334    server.addConnector(serverConnector);
335    server.setStopAtShutdown(true);
336
337    // set up context
338    ServletContextHandler ctxHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
339    ctxHandler.addServlet(sh, PATH_SPEC_ANY);
340    if (authFilter != null) {
341      ctxHandler.addFilter(authFilter, PATH_SPEC_ANY, EnumSet.of(DispatcherType.REQUEST));
342    }
343
344    // Load filters from configuration.
345    String[] filterClasses = servlet.getConfiguration().getStrings(FILTER_CLASSES,
346        GzipFilter.class.getName());
347    for (String filter : filterClasses) {
348      filter = filter.trim();
349      ctxHandler.addFilter(filter, PATH_SPEC_ANY, EnumSet.of(DispatcherType.REQUEST));
350    }
351    addCSRFFilter(ctxHandler, conf);
352    HttpServerUtil.constrainHttpMethods(ctxHandler, servlet.getConfiguration()
353        .getBoolean(REST_HTTP_ALLOW_OPTIONS_METHOD, REST_HTTP_ALLOW_OPTIONS_METHOD_DEFAULT));
354
355    // Put up info server.
356    int port = conf.getInt("hbase.rest.info.port", 8085);
357    if (port >= 0) {
358      conf.setLong("startcode", System.currentTimeMillis());
359      String a = conf.get("hbase.rest.info.bindAddress", "0.0.0.0");
360      this.infoServer = new InfoServer("rest", a, port, false, conf);
361      this.infoServer.setAttribute("hbase.conf", conf);
362      this.infoServer.start();
363    }
364    try {
365      // start server
366      server.start();
367    } catch (Exception e) {
368      LOG.error(HBaseMarkers.FATAL, "Failed to start server", e);
369      throw e;
370    }
371  }
372
373  public synchronized void join() throws Exception {
374    if (server == null) {
375      throw new IllegalStateException("Server is not running");
376    }
377    server.join();
378  }
379
380  public synchronized void stop() throws Exception {
381    if (server == null) {
382      throw new IllegalStateException("Server is not running");
383    }
384    server.stop();
385    server = null;
386    RESTServlet.stop();
387  }
388
389  public synchronized int getPort() {
390    if (server == null) {
391      throw new IllegalStateException("Server is not running");
392    }
393    return ((ServerConnector) server.getConnectors()[0]).getLocalPort();
394  }
395
396  @SuppressWarnings("deprecation")
397  public synchronized int getInfoPort() {
398    if (infoServer == null) {
399      throw new IllegalStateException("InfoServer is not running");
400    }
401    return infoServer.getPort();
402  }
403
404  public Configuration getConf() {
405    return conf;
406  }
407
408  /**
409   * The main method for the HBase rest server.
410   * @param args command-line arguments
411   * @throws Exception exception
412   */
413  public static void main(String[] args) throws Exception {
414    LOG.info("***** STARTING service '" + RESTServer.class.getSimpleName() + "' *****");
415    VersionInfo.logVersion();
416    final Configuration conf = HBaseConfiguration.create();
417    parseCommandLine(args, conf);
418    RESTServer server = new RESTServer(conf);
419
420    try {
421      server.run();
422      server.join();
423    } catch (Exception e) {
424      System.exit(1);
425    }
426
427    LOG.info("***** STOPPING service '" + RESTServer.class.getSimpleName() + "' *****");
428  }
429}