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 com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
022import java.lang.management.ManagementFactory;
023import java.util.ArrayList;
024import java.util.EnumSet;
025import java.util.List;
026import java.util.Map;
027import java.util.concurrent.ArrayBlockingQueue;
028import javax.servlet.DispatcherType;
029import org.apache.commons.lang3.ArrayUtils;
030import org.apache.hadoop.conf.Configuration;
031import org.apache.hadoop.hbase.HBaseConfiguration;
032import org.apache.hadoop.hbase.HBaseInterfaceAudience;
033import org.apache.hadoop.hbase.http.ClickjackingPreventionFilter;
034import org.apache.hadoop.hbase.http.HttpServerUtil;
035import org.apache.hadoop.hbase.http.InfoServer;
036import org.apache.hadoop.hbase.http.SecurityHeadersFilter;
037import org.apache.hadoop.hbase.log.HBaseMarkers;
038import org.apache.hadoop.hbase.rest.filter.AuthFilter;
039import org.apache.hadoop.hbase.rest.filter.GzipFilter;
040import org.apache.hadoop.hbase.rest.filter.RestCsrfPreventionFilter;
041import org.apache.hadoop.hbase.security.UserProvider;
042import org.apache.hadoop.hbase.util.DNS;
043import org.apache.hadoop.hbase.util.Pair;
044import org.apache.hadoop.hbase.util.ReflectionUtils;
045import org.apache.hadoop.hbase.util.Strings;
046import org.apache.hadoop.hbase.util.VersionInfo;
047import org.apache.yetus.audience.InterfaceAudience;
048import org.eclipse.jetty.http.HttpVersion;
049import org.eclipse.jetty.jmx.MBeanContainer;
050import org.eclipse.jetty.server.HttpConfiguration;
051import org.eclipse.jetty.server.HttpConnectionFactory;
052import org.eclipse.jetty.server.SecureRequestCustomizer;
053import org.eclipse.jetty.server.Server;
054import org.eclipse.jetty.server.ServerConnector;
055import org.eclipse.jetty.server.SslConnectionFactory;
056import org.eclipse.jetty.servlet.FilterHolder;
057import org.eclipse.jetty.servlet.ServletContextHandler;
058import org.eclipse.jetty.servlet.ServletHolder;
059import org.eclipse.jetty.util.ssl.SslContextFactory;
060import org.eclipse.jetty.util.thread.QueuedThreadPool;
061import org.glassfish.jersey.server.ResourceConfig;
062import org.glassfish.jersey.servlet.ServletContainer;
063import org.slf4j.Logger;
064import org.slf4j.LoggerFactory;
065import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
066import org.apache.hbase.thirdparty.org.apache.commons.cli.CommandLine;
067import org.apache.hbase.thirdparty.org.apache.commons.cli.HelpFormatter;
068import org.apache.hbase.thirdparty.org.apache.commons.cli.Options;
069import org.apache.hbase.thirdparty.org.apache.commons.cli.ParseException;
070import org.apache.hbase.thirdparty.org.apache.commons.cli.PosixParser;
071
072/**
073 * Main class for launching REST gateway as a servlet hosted by Jetty.
074 * <p>
075 * The following options are supported:
076 * <ul>
077 * <li>-p --port : service port</li>
078 * <li>-ro --readonly : server mode</li>
079 * </ul>
080 */
081@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
082public class RESTServer implements Constants {
083  static Logger LOG = LoggerFactory.getLogger("RESTServer");
084
085  static final String REST_CSRF_ENABLED_KEY = "hbase.rest.csrf.enabled";
086  static final boolean REST_CSRF_ENABLED_DEFAULT = false;
087  boolean restCSRFEnabled = false;
088  static final String REST_CSRF_CUSTOM_HEADER_KEY ="hbase.rest.csrf.custom.header";
089  static final String REST_CSRF_CUSTOM_HEADER_DEFAULT = "X-XSRF-HEADER";
090  static final String REST_CSRF_METHODS_TO_IGNORE_KEY = "hbase.rest.csrf.methods.to.ignore";
091  static final String REST_CSRF_METHODS_TO_IGNORE_DEFAULT = "GET,OPTIONS,HEAD,TRACE";
092  public static final String SKIP_LOGIN_KEY = "hbase.rest.skip.login";
093  static final int DEFAULT_HTTP_MAX_HEADER_SIZE = 64 * 1024; // 64k
094
095  private static final String PATH_SPEC_ANY = "/*";
096
097  static final String REST_HTTP_ALLOW_OPTIONS_METHOD = "hbase.rest.http.allow.options.method";
098  // HTTP OPTIONS method is commonly used in REST APIs for negotiation. So it is enabled by default.
099  private static boolean REST_HTTP_ALLOW_OPTIONS_METHOD_DEFAULT = true;
100  static final String REST_CSRF_BROWSER_USERAGENTS_REGEX_KEY =
101    "hbase.rest-csrf.browser-useragents-regex";
102
103  // HACK, making this static for AuthFilter to get at our configuration. Necessary for unit tests.
104  @edu.umd.cs.findbugs.annotations.SuppressWarnings(
105    value={"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", "MS_CANNOT_BE_FINAL"},
106    justification="For testing")
107  public static Configuration conf = null;
108  private final UserProvider userProvider;
109  private Server server;
110  private InfoServer infoServer;
111
112  public RESTServer(Configuration conf) {
113    RESTServer.conf = conf;
114    this.userProvider = UserProvider.instantiate(conf);
115  }
116
117  private static void printUsageAndExit(Options options, int exitCode) {
118    HelpFormatter formatter = new HelpFormatter();
119    formatter.printHelp("hbase rest start", "", options,
120      "\nTo run the REST server as a daemon, execute " +
121      "hbase-daemon.sh start|stop rest [-i <port>] [-p <port>] [-ro]\n", true);
122    System.exit(exitCode);
123  }
124
125  void addCSRFFilter(ServletContextHandler ctxHandler, Configuration conf) {
126    restCSRFEnabled = conf.getBoolean(REST_CSRF_ENABLED_KEY, REST_CSRF_ENABLED_DEFAULT);
127    if (restCSRFEnabled) {
128      Map<String, String> restCsrfParams = RestCsrfPreventionFilter
129          .getFilterParams(conf, "hbase.rest-csrf.");
130      FilterHolder holder = new FilterHolder();
131      holder.setName("csrf");
132      holder.setClassName(RestCsrfPreventionFilter.class.getName());
133      holder.setInitParameters(restCsrfParams);
134      ctxHandler.addFilter(holder, PATH_SPEC_ANY, EnumSet.allOf(DispatcherType.class));
135    }
136  }
137
138  private void addClickjackingPreventionFilter(ServletContextHandler ctxHandler,
139      Configuration conf) {
140    FilterHolder holder = new FilterHolder();
141    holder.setName("clickjackingprevention");
142    holder.setClassName(ClickjackingPreventionFilter.class.getName());
143    holder.setInitParameters(ClickjackingPreventionFilter.getDefaultParameters(conf));
144    ctxHandler.addFilter(holder, PATH_SPEC_ANY, EnumSet.allOf(DispatcherType.class));
145  }
146
147  private void addSecurityHeadersFilter(ServletContextHandler ctxHandler, Configuration conf) {
148    FilterHolder holder = new FilterHolder();
149    holder.setName("securityheaders");
150    holder.setClassName(SecurityHeadersFilter.class.getName());
151    holder.setInitParameters(SecurityHeadersFilter.getDefaultParameters(conf));
152    ctxHandler.addFilter(holder, PATH_SPEC_ANY, EnumSet.allOf(DispatcherType.class));
153  }
154
155  // login the server principal (if using secure Hadoop)
156  private static Pair<FilterHolder, Class<? extends ServletContainer>> loginServerPrincipal(
157    UserProvider userProvider, Configuration conf) throws Exception {
158    Class<? extends ServletContainer> containerClass = ServletContainer.class;
159    if (userProvider.isHadoopSecurityEnabled() && userProvider.isHBaseSecurityEnabled()) {
160      String machineName = Strings.domainNamePointerToHostName(
161        DNS.getDefaultHost(conf.get(REST_DNS_INTERFACE, "default"),
162          conf.get(REST_DNS_NAMESERVER, "default")));
163      String keytabFilename = conf.get(REST_KEYTAB_FILE);
164      Preconditions.checkArgument(keytabFilename != null && !keytabFilename.isEmpty(),
165        REST_KEYTAB_FILE + " should be set if security is enabled");
166      String principalConfig = conf.get(REST_KERBEROS_PRINCIPAL);
167      Preconditions.checkArgument(principalConfig != null && !principalConfig.isEmpty(),
168        REST_KERBEROS_PRINCIPAL + " should be set if security is enabled");
169      // Hook for unit tests, this will log out any other user and mess up tests.
170      if (!conf.getBoolean(SKIP_LOGIN_KEY, false)) {
171        userProvider.login(REST_KEYTAB_FILE, REST_KERBEROS_PRINCIPAL, machineName);
172      }
173      if (conf.get(REST_AUTHENTICATION_TYPE) != null) {
174        containerClass = RESTServletContainer.class;
175        FilterHolder authFilter = new FilterHolder();
176        authFilter.setClassName(AuthFilter.class.getName());
177        authFilter.setName("AuthenticationFilter");
178        return new Pair<>(authFilter,containerClass);
179      }
180    }
181    return new Pair<>(null, containerClass);
182  }
183
184  private static void parseCommandLine(String[] args, Configuration conf) {
185    Options options = new Options();
186    options.addOption("p", "port", true, "Port to bind to [default: " + DEFAULT_LISTEN_PORT + "]");
187    options.addOption("ro", "readonly", false, "Respond only to GET HTTP " +
188      "method requests [default: false]");
189    options.addOption("i", "infoport", true, "Port for WEB UI");
190
191    CommandLine commandLine = null;
192    try {
193      commandLine = new PosixParser().parse(options, args);
194    } catch (ParseException e) {
195      LOG.error("Could not parse: ", e);
196      printUsageAndExit(options, -1);
197    }
198
199    // check for user-defined port setting, if so override the conf
200    if (commandLine != null && commandLine.hasOption("port")) {
201      String val = commandLine.getOptionValue("port");
202      conf.setInt("hbase.rest.port", Integer.parseInt(val));
203      if (LOG.isDebugEnabled()) {
204        LOG.debug("port set to " + val);
205      }
206    }
207
208    // check if server should only process GET requests, if so override the conf
209    if (commandLine != null && commandLine.hasOption("readonly")) {
210      conf.setBoolean("hbase.rest.readonly", true);
211      if (LOG.isDebugEnabled()) {
212        LOG.debug("readonly set to true");
213      }
214    }
215
216    // check for user-defined info server port setting, if so override the conf
217    if (commandLine != null && commandLine.hasOption("infoport")) {
218      String val = commandLine.getOptionValue("infoport");
219      conf.setInt("hbase.rest.info.port", Integer.parseInt(val));
220      if (LOG.isDebugEnabled()) {
221        LOG.debug("WEB UI port set to " + val);
222      }
223    }
224
225    if (commandLine != null && commandLine.hasOption("skipLogin")) {
226      conf.setBoolean(SKIP_LOGIN_KEY, true);
227      if (LOG.isDebugEnabled()) {
228        LOG.debug("Skipping Kerberos login for REST server");
229      }
230    }
231
232    List<String> remainingArgs = commandLine != null ? commandLine.getArgList() : new ArrayList<>();
233    if (remainingArgs.size() != 1) {
234      printUsageAndExit(options, 1);
235    }
236
237    String command = remainingArgs.get(0);
238    if ("start".equals(command)) {
239      // continue and start container
240    } else if ("stop".equals(command)) {
241      System.exit(1);
242    } else {
243      printUsageAndExit(options, 1);
244    }
245  }
246
247
248  /**
249   * Runs the REST server.
250   */
251  public synchronized void run() throws Exception {
252    Pair<FilterHolder, Class<? extends ServletContainer>> pair = loginServerPrincipal(
253      userProvider, conf);
254    FilterHolder authFilter = pair.getFirst();
255    Class<? extends ServletContainer> containerClass = pair.getSecond();
256    RESTServlet servlet = RESTServlet.getInstance(conf, userProvider);
257
258
259    // Set up the Jersey servlet container for Jetty
260    // The Jackson1Feature is a signal to Jersey that it should use jackson doing json.
261    // See here: https://stackoverflow.com/questions/39458230/how-register-jacksonfeature-on-clientconfig
262    ResourceConfig application = new ResourceConfig().
263        packages("org.apache.hadoop.hbase.rest").register(JacksonJaxbJsonProvider.class);
264    // Using our custom ServletContainer is tremendously important. This is what makes sure the
265    // UGI.doAs() is done for the remoteUser, and calls are not made as the REST server itself.
266    ServletContainer servletContainer = ReflectionUtils.newInstance(containerClass, application);
267    ServletHolder sh = new ServletHolder(servletContainer);
268
269    // Set the default max thread number to 100 to limit
270    // the number of concurrent requests so that REST server doesn't OOM easily.
271    // Jetty set the default max thread number to 250, if we don't set it.
272    //
273    // Our default min thread number 2 is the same as that used by Jetty.
274    int maxThreads = servlet.getConfiguration().getInt(REST_THREAD_POOL_THREADS_MAX, 100);
275    int minThreads = servlet.getConfiguration().getInt(REST_THREAD_POOL_THREADS_MIN, 2);
276    // Use the default queue (unbounded with Jetty 9.3) if the queue size is negative, otherwise use
277    // bounded {@link ArrayBlockingQueue} with the given size
278    int queueSize = servlet.getConfiguration().getInt(REST_THREAD_POOL_TASK_QUEUE_SIZE, -1);
279    int idleTimeout = servlet.getConfiguration().getInt(REST_THREAD_POOL_THREAD_IDLE_TIMEOUT, 60000);
280    QueuedThreadPool threadPool = queueSize > 0 ?
281        new QueuedThreadPool(maxThreads, minThreads, idleTimeout, new ArrayBlockingQueue<>(queueSize)) :
282        new QueuedThreadPool(maxThreads, minThreads, idleTimeout);
283
284    this.server = new Server(threadPool);
285
286    // Setup JMX
287    MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
288    server.addEventListener(mbContainer);
289    server.addBean(mbContainer);
290
291
292    String host = servlet.getConfiguration().get("hbase.rest.host", "0.0.0.0");
293    int servicePort = servlet.getConfiguration().getInt("hbase.rest.port", 8080);
294    HttpConfiguration httpConfig = new HttpConfiguration();
295    httpConfig.setSecureScheme("https");
296    httpConfig.setSecurePort(servicePort);
297    httpConfig.setHeaderCacheSize(DEFAULT_HTTP_MAX_HEADER_SIZE);
298    httpConfig.setRequestHeaderSize(DEFAULT_HTTP_MAX_HEADER_SIZE);
299    httpConfig.setResponseHeaderSize(DEFAULT_HTTP_MAX_HEADER_SIZE);
300    httpConfig.setSendServerVersion(false);
301    httpConfig.setSendDateHeader(false);
302
303    ServerConnector serverConnector;
304    if (conf.getBoolean(REST_SSL_ENABLED, false)) {
305      HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
306      httpsConfig.addCustomizer(new SecureRequestCustomizer());
307
308      SslContextFactory sslCtxFactory = new SslContextFactory();
309      String keystore = conf.get(REST_SSL_KEYSTORE_STORE);
310      String password = HBaseConfiguration.getPassword(conf,
311          REST_SSL_KEYSTORE_PASSWORD, null);
312      String keyPassword = HBaseConfiguration.getPassword(conf,
313          REST_SSL_KEYSTORE_KEYPASSWORD, password);
314      sslCtxFactory.setKeyStorePath(keystore);
315      sslCtxFactory.setKeyStorePassword(password);
316      sslCtxFactory.setKeyManagerPassword(keyPassword);
317
318      String[] excludeCiphers = servlet.getConfiguration().getStrings(
319          REST_SSL_EXCLUDE_CIPHER_SUITES, ArrayUtils.EMPTY_STRING_ARRAY);
320      if (excludeCiphers.length != 0) {
321        sslCtxFactory.setExcludeCipherSuites(excludeCiphers);
322      }
323      String[] includeCiphers = servlet.getConfiguration().getStrings(
324          REST_SSL_INCLUDE_CIPHER_SUITES, ArrayUtils.EMPTY_STRING_ARRAY);
325      if (includeCiphers.length != 0) {
326        sslCtxFactory.setIncludeCipherSuites(includeCiphers);
327      }
328
329      String[] excludeProtocols = servlet.getConfiguration().getStrings(
330          REST_SSL_EXCLUDE_PROTOCOLS, ArrayUtils.EMPTY_STRING_ARRAY);
331      if (excludeProtocols.length != 0) {
332        sslCtxFactory.setExcludeProtocols(excludeProtocols);
333      }
334      String[] includeProtocols = servlet.getConfiguration().getStrings(
335          REST_SSL_INCLUDE_PROTOCOLS, ArrayUtils.EMPTY_STRING_ARRAY);
336      if (includeProtocols.length != 0) {
337        sslCtxFactory.setIncludeProtocols(includeProtocols);
338      }
339
340      serverConnector = new ServerConnector(server,
341          new SslConnectionFactory(sslCtxFactory, HttpVersion.HTTP_1_1.toString()),
342          new HttpConnectionFactory(httpsConfig));
343    } else {
344      serverConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
345    }
346
347    int acceptQueueSize = servlet.getConfiguration().getInt(REST_CONNECTOR_ACCEPT_QUEUE_SIZE, -1);
348    if (acceptQueueSize >= 0) {
349      serverConnector.setAcceptQueueSize(acceptQueueSize);
350    }
351
352    serverConnector.setPort(servicePort);
353    serverConnector.setHost(host);
354
355    server.addConnector(serverConnector);
356    server.setStopAtShutdown(true);
357
358    // set up context
359    ServletContextHandler ctxHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
360    ctxHandler.addServlet(sh, PATH_SPEC_ANY);
361    if (authFilter != null) {
362      ctxHandler.addFilter(authFilter, PATH_SPEC_ANY, EnumSet.of(DispatcherType.REQUEST));
363    }
364
365    // Load filters from configuration.
366    String[] filterClasses = servlet.getConfiguration().getStrings(FILTER_CLASSES,
367        GzipFilter.class.getName());
368    for (String filter : filterClasses) {
369      filter = filter.trim();
370      ctxHandler.addFilter(filter, PATH_SPEC_ANY, EnumSet.of(DispatcherType.REQUEST));
371    }
372    addCSRFFilter(ctxHandler, conf);
373    addClickjackingPreventionFilter(ctxHandler, conf);
374    addSecurityHeadersFilter(ctxHandler, conf);
375    HttpServerUtil.constrainHttpMethods(ctxHandler, servlet.getConfiguration()
376        .getBoolean(REST_HTTP_ALLOW_OPTIONS_METHOD, REST_HTTP_ALLOW_OPTIONS_METHOD_DEFAULT));
377
378    // Put up info server.
379    int port = conf.getInt("hbase.rest.info.port", 8085);
380    if (port >= 0) {
381      conf.setLong("startcode", System.currentTimeMillis());
382      String a = conf.get("hbase.rest.info.bindAddress", "0.0.0.0");
383      this.infoServer = new InfoServer("rest", a, port, false, conf);
384      this.infoServer.setAttribute("hbase.conf", conf);
385      this.infoServer.start();
386    }
387    try {
388      // start server
389      server.start();
390    } catch (Exception e) {
391      LOG.error(HBaseMarkers.FATAL, "Failed to start server", e);
392      throw e;
393    }
394  }
395
396  public synchronized void join() throws Exception {
397    if (server == null) {
398      throw new IllegalStateException("Server is not running");
399    }
400    server.join();
401  }
402
403  public synchronized void stop() throws Exception {
404    if (server == null) {
405      throw new IllegalStateException("Server is not running");
406    }
407    server.stop();
408    server = null;
409    RESTServlet.stop();
410  }
411
412  public synchronized int getPort() {
413    if (server == null) {
414      throw new IllegalStateException("Server is not running");
415    }
416    return ((ServerConnector) server.getConnectors()[0]).getLocalPort();
417  }
418
419  @SuppressWarnings("deprecation")
420  public synchronized int getInfoPort() {
421    if (infoServer == null) {
422      throw new IllegalStateException("InfoServer is not running");
423    }
424    return infoServer.getPort();
425  }
426
427  public Configuration getConf() {
428    return conf;
429  }
430
431  /**
432   * The main method for the HBase rest server.
433   * @param args command-line arguments
434   * @throws Exception exception
435   */
436  public static void main(String[] args) throws Exception {
437    LOG.info("***** STARTING service '" + RESTServer.class.getSimpleName() + "' *****");
438    VersionInfo.logVersion();
439    final Configuration conf = HBaseConfiguration.create();
440    parseCommandLine(args, conf);
441    RESTServer server = new RESTServer(conf);
442
443    try {
444      server.run();
445      server.join();
446    } catch (Exception e) {
447      System.exit(1);
448    }
449
450    LOG.info("***** STOPPING service '" + RESTServer.class.getSimpleName() + "' *****");
451  }
452}