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