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 // Intended for unit tests 096 public static final String SKIP_LOGIN_KEY = "hbase.rest.skip.login"; 097 098 private static final String PATH_SPEC_ANY = "/*"; 099 100 static final String REST_HTTP_ALLOW_OPTIONS_METHOD = "hbase.rest.http.allow.options.method"; 101 // HTTP OPTIONS method is commonly used in REST APIs for negotiation. So it is enabled by default. 102 private static boolean REST_HTTP_ALLOW_OPTIONS_METHOD_DEFAULT = true; 103 static final String REST_CSRF_BROWSER_USERAGENTS_REGEX_KEY = 104 "hbase.rest-csrf.browser-useragents-regex"; 105 106 // HACK, making this static for AuthFilter to get at our configuration. Necessary for unit tests. 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 [--infoport <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 // login the server principal (if using secure Hadoop) 139 private static Pair<FilterHolder, Class<? extends ServletContainer>> loginServerPrincipal( 140 UserProvider userProvider, Configuration conf) throws Exception { 141 Class<? extends ServletContainer> containerClass = ServletContainer.class; 142 if (userProvider.isHadoopSecurityEnabled() && userProvider.isHBaseSecurityEnabled()) { 143 String machineName = Strings.domainNamePointerToHostName( 144 DNS.getDefaultHost(conf.get(REST_DNS_INTERFACE, "default"), 145 conf.get(REST_DNS_NAMESERVER, "default"))); 146 String keytabFilename = conf.get(REST_KEYTAB_FILE); 147 Preconditions.checkArgument(keytabFilename != null && !keytabFilename.isEmpty(), 148 REST_KEYTAB_FILE + " should be set if security is enabled"); 149 String principalConfig = conf.get(REST_KERBEROS_PRINCIPAL); 150 Preconditions.checkArgument(principalConfig != null && !principalConfig.isEmpty(), 151 REST_KERBEROS_PRINCIPAL + " should be set if security is enabled"); 152 // Hook for unit tests, this will log out any other user and mess up tests. 153 if (!conf.getBoolean(SKIP_LOGIN_KEY, false)) { 154 userProvider.login(REST_KEYTAB_FILE, REST_KERBEROS_PRINCIPAL, machineName); 155 } 156 if (conf.get(REST_AUTHENTICATION_TYPE) != null) { 157 containerClass = RESTServletContainer.class; 158 FilterHolder authFilter = new FilterHolder(); 159 authFilter.setClassName(AuthFilter.class.getName()); 160 authFilter.setName("AuthenticationFilter"); 161 return new Pair<>(authFilter,containerClass); 162 } 163 } 164 return new Pair<>(null, containerClass); 165 } 166 167 private static void parseCommandLine(String[] args, Configuration conf) { 168 Options options = new Options(); 169 options.addOption("p", "port", true, "Port to bind to [default: " + DEFAULT_LISTEN_PORT + "]"); 170 options.addOption("ro", "readonly", false, "Respond only to GET HTTP " + 171 "method requests [default: false]"); 172 options.addOption(null, "infoport", true, "Port for web UI"); 173 174 CommandLine commandLine = null; 175 try { 176 commandLine = new PosixParser().parse(options, args); 177 } catch (ParseException e) { 178 LOG.error("Could not parse: ", e); 179 printUsageAndExit(options, -1); 180 } 181 182 // check for user-defined port setting, if so override the conf 183 if (commandLine != null && commandLine.hasOption("port")) { 184 String val = commandLine.getOptionValue("port"); 185 conf.setInt("hbase.rest.port", Integer.parseInt(val)); 186 if (LOG.isDebugEnabled()) { 187 LOG.debug("port set to " + val); 188 } 189 } 190 191 // check if server should only process GET requests, if so override the conf 192 if (commandLine != null && commandLine.hasOption("readonly")) { 193 conf.setBoolean("hbase.rest.readonly", true); 194 if (LOG.isDebugEnabled()) { 195 LOG.debug("readonly set to true"); 196 } 197 } 198 199 // check for user-defined info server port setting, if so override the conf 200 if (commandLine != null && commandLine.hasOption("infoport")) { 201 String val = commandLine.getOptionValue("infoport"); 202 conf.setInt("hbase.rest.info.port", Integer.parseInt(val)); 203 if (LOG.isDebugEnabled()) { 204 LOG.debug("Web UI port set to " + val); 205 } 206 } 207 208 if (commandLine != null && commandLine.hasOption("skipLogin")) { 209 conf.setBoolean(SKIP_LOGIN_KEY, true); 210 LOG.warn("Skipping Kerberos login for REST server"); 211 } 212 213 List<String> remainingArgs = commandLine != null ? commandLine.getArgList() : new ArrayList<>(); 214 if (remainingArgs.size() != 1) { 215 printUsageAndExit(options, 1); 216 } 217 218 String command = remainingArgs.get(0); 219 if ("start".equals(command)) { 220 // continue and start container 221 } else if ("stop".equals(command)) { 222 System.exit(1); 223 } else { 224 printUsageAndExit(options, 1); 225 } 226 } 227 228 229 /** 230 * Runs the REST server. 231 */ 232 public synchronized void run() throws Exception { 233 Pair<FilterHolder, Class<? extends ServletContainer>> pair = loginServerPrincipal( 234 userProvider, conf); 235 FilterHolder authFilter = pair.getFirst(); 236 Class<? extends ServletContainer> containerClass = pair.getSecond(); 237 RESTServlet servlet = RESTServlet.getInstance(conf, userProvider); 238 239 240 // Set up the Jersey servlet container for Jetty 241 // The Jackson1Feature is a signal to Jersey that it should use jackson doing json. 242 // See here: https://stackoverflow.com/questions/39458230/how-register-jacksonfeature-on-clientconfig 243 ResourceConfig application = new ResourceConfig(). 244 packages("org.apache.hadoop.hbase.rest").register(JacksonJaxbJsonProvider.class); 245 // Using our custom ServletContainer is tremendously important. This is what makes sure the 246 // UGI.doAs() is done for the remoteUser, and calls are not made as the REST server itself. 247 ServletContainer servletContainer = ReflectionUtils.newInstance(containerClass, application); 248 ServletHolder sh = new ServletHolder(servletContainer); 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 this.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 this.infoServer = new InfoServer("rest", a, port, false, conf); 360 this.infoServer.setAttribute("hbase.conf", conf); 361 this.infoServer.start(); 362 } 363 try { 364 // start server 365 server.start(); 366 } catch (Exception e) { 367 LOG.error(HBaseMarkers.FATAL, "Failed to start server", e); 368 throw e; 369 } 370 } 371 372 public synchronized void join() throws Exception { 373 if (server == null) { 374 throw new IllegalStateException("Server is not running"); 375 } 376 server.join(); 377 } 378 379 public synchronized void stop() throws Exception { 380 if (server == null) { 381 throw new IllegalStateException("Server is not running"); 382 } 383 server.stop(); 384 server = null; 385 RESTServlet.stop(); 386 } 387 388 public synchronized int getPort() { 389 if (server == null) { 390 throw new IllegalStateException("Server is not running"); 391 } 392 return ((ServerConnector) server.getConnectors()[0]).getLocalPort(); 393 } 394 395 @SuppressWarnings("deprecation") 396 public synchronized int getInfoPort() { 397 if (infoServer == null) { 398 throw new IllegalStateException("InfoServer is not running"); 399 } 400 return infoServer.getPort(); 401 } 402 403 public Configuration getConf() { 404 return conf; 405 } 406 407 /** 408 * The main method for the HBase rest server. 409 * @param args command-line arguments 410 * @throws Exception exception 411 */ 412 public static void main(String[] args) throws Exception { 413 LOG.info("***** STARTING service '" + RESTServer.class.getSimpleName() + "' *****"); 414 VersionInfo.logVersion(); 415 final Configuration conf = HBaseConfiguration.create(); 416 parseCommandLine(args, conf); 417 RESTServer server = new RESTServer(conf); 418 419 try { 420 server.run(); 421 server.join(); 422 } catch (Exception e) { 423 System.exit(1); 424 } 425 426 LOG.info("***** STOPPING service '" + RESTServer.class.getSimpleName() + "' *****"); 427 } 428}