Search in sources :

Example 41 with FilterHolder

use of org.eclipse.jetty.servlet.FilterHolder in project lucene-solr by apache.

the class JettySolrRunner method stop.

/**
   * Stop the Jetty server
   *
   * @throws Exception if an error occurs on shutdown
   */
public void stop() throws Exception {
    // Do not let Jetty/Solr pollute the MDC for this thread
    Map<String, String> prevContext = MDC.getCopyOfContextMap();
    MDC.clear();
    try {
        Filter filter = dispatchFilter.getFilter();
        server.stop();
        if (server.getState().equals(Server.FAILED)) {
            filter.destroy();
            if (extraFilters != null) {
                for (FilterHolder f : extraFilters) {
                    f.getFilter().destroy();
                }
            }
        }
        server.join();
    } finally {
        if (prevContext != null) {
            MDC.setContextMap(prevContext);
        } else {
            MDC.clear();
        }
    }
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) SolrDispatchFilter(org.apache.solr.servlet.SolrDispatchFilter) Filter(javax.servlet.Filter)

Example 42 with FilterHolder

use of org.eclipse.jetty.servlet.FilterHolder in project gerrit by GerritCodeReview.

the class JettyServer method makeContext.

private ContextHandler makeContext(final String contextPath, final JettyEnv env, final Config cfg) {
    final ServletContextHandler app = new ServletContextHandler();
    // This enables the use of sessions in Jetty, feature available
    // for Gerrit plug-ins to enable user-level sessions.
    //
    app.setSessionHandler(new SessionHandler());
    app.setErrorHandler(new HiddenErrorHandler());
    // This is the path we are accessed by clients within our domain.
    //
    app.setContextPath(contextPath);
    // HTTP front-end filters to be used as surrogate of Apache HTTP
    // reverse-proxy filtering.
    // It is meant to be used as simpler tiny deployment of custom-made
    // security enforcement (Security tokens, IP-based security filtering, others)
    String[] filterClassNames = cfg.getStringList("httpd", null, "filterClass");
    for (String filterClassName : filterClassNames) {
        try {
            @SuppressWarnings("unchecked") Class<? extends Filter> filterClass = (Class<? extends Filter>) Class.forName(filterClassName);
            Filter filter = env.webInjector.getInstance(filterClass);
            app.addFilter(new FilterHolder(filter), "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC));
        } catch (Throwable e) {
            String errorMessage = "Unable to instantiate front-end HTTP Filter " + filterClassName;
            log.error(errorMessage, e);
            throw new IllegalArgumentException(errorMessage, e);
        }
    }
    // Perform the same binding as our web.xml would do, but instead
    // of using the listener to create the injector pass the one we
    // already have built.
    //
    GuiceFilter filter = env.webInjector.getInstance(GuiceFilter.class);
    app.addFilter(new FilterHolder(filter), "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC));
    app.addEventListener(new GuiceServletContextListener() {

        @Override
        protected Injector getInjector() {
            return env.webInjector;
        }
    });
    // Jetty requires at least one servlet be bound before it will
    // bother running the filter above. Since the filter has all
    // of our URLs except the static resources, the only servlet
    // we need to bind is the default static resource servlet from
    // the Jetty container.
    //
    final ServletHolder ds = app.addServlet(DefaultServlet.class, "/");
    ds.setInitParameter("dirAllowed", "false");
    ds.setInitParameter("redirectWelcome", "false");
    ds.setInitParameter("useFileMappedBuffer", "false");
    ds.setInitParameter("gzip", "true");
    app.setWelcomeFiles(new String[0]);
    return app;
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) GuiceFilter(com.google.inject.servlet.GuiceFilter) Filter(javax.servlet.Filter) GuiceFilter(com.google.inject.servlet.GuiceFilter) Injector(com.google.inject.Injector) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) GuiceServletContextListener(com.google.inject.servlet.GuiceServletContextListener)

Example 43 with FilterHolder

use of org.eclipse.jetty.servlet.FilterHolder in project hbase by apache.

the class RESTServer method main.

/**
   * The main method for the HBase rest server.
   * @param args command-line arguments
   * @throws Exception exception
   */
public static void main(String[] args) throws Exception {
    LOG.info("***** STARTING service '" + RESTServer.class.getSimpleName() + "' *****");
    VersionInfo.logVersion();
    Configuration conf = HBaseConfiguration.create();
    UserProvider userProvider = UserProvider.instantiate(conf);
    Pair<FilterHolder, Class<? extends ServletContainer>> pair = loginServerPrincipal(userProvider, conf);
    FilterHolder authFilter = pair.getFirst();
    RESTServlet servlet = RESTServlet.getInstance(conf, userProvider);
    parseCommandLine(args, servlet);
    // set up the Jersey servlet container for Jetty
    ResourceConfig application = new ResourceConfig().packages("org.apache.hadoop.hbase.rest").register(Jackson1Feature.class);
    ServletHolder sh = new ServletHolder(new ServletContainer(application));
    // Set the default max thread number to 100 to limit
    // the number of concurrent requests so that REST server doesn't OOM easily.
    // Jetty set the default max thread number to 250, if we don't set it.
    //
    // Our default min thread number 2 is the same as that used by Jetty.
    int maxThreads = servlet.getConfiguration().getInt(REST_THREAD_POOL_THREADS_MAX, 100);
    int minThreads = servlet.getConfiguration().getInt(REST_THREAD_POOL_THREADS_MIN, 2);
    // Use the default queue (unbounded with Jetty 9.3) if the queue size is negative, otherwise use
    // bounded {@link ArrayBlockingQueue} with the given size
    int queueSize = servlet.getConfiguration().getInt(REST_THREAD_POOL_TASK_QUEUE_SIZE, -1);
    int idleTimeout = servlet.getConfiguration().getInt(REST_THREAD_POOL_THREAD_IDLE_TIMEOUT, 60000);
    QueuedThreadPool threadPool = queueSize > 0 ? new QueuedThreadPool(maxThreads, minThreads, idleTimeout, new ArrayBlockingQueue<>(queueSize)) : new QueuedThreadPool(maxThreads, minThreads, idleTimeout);
    Server server = new Server(threadPool);
    // Setup JMX
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addEventListener(mbContainer);
    server.addBean(mbContainer);
    String host = servlet.getConfiguration().get("hbase.rest.host", "0.0.0.0");
    int servicePort = servlet.getConfiguration().getInt("hbase.rest.port", 8080);
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSecureScheme("https");
    httpConfig.setSecurePort(servicePort);
    httpConfig.setSendServerVersion(false);
    httpConfig.setSendDateHeader(false);
    ServerConnector serverConnector;
    if (conf.getBoolean(REST_SSL_ENABLED, false)) {
        HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
        httpsConfig.addCustomizer(new SecureRequestCustomizer());
        SslContextFactory sslCtxFactory = new SslContextFactory();
        String keystore = conf.get(REST_SSL_KEYSTORE_STORE);
        String password = HBaseConfiguration.getPassword(conf, REST_SSL_KEYSTORE_PASSWORD, null);
        String keyPassword = HBaseConfiguration.getPassword(conf, REST_SSL_KEYSTORE_KEYPASSWORD, password);
        sslCtxFactory.setKeyStorePath(keystore);
        sslCtxFactory.setKeyStorePassword(password);
        sslCtxFactory.setKeyManagerPassword(keyPassword);
        String[] excludeCiphers = servlet.getConfiguration().getStrings(REST_SSL_EXCLUDE_CIPHER_SUITES, ArrayUtils.EMPTY_STRING_ARRAY);
        if (excludeCiphers.length != 0) {
            sslCtxFactory.setExcludeCipherSuites(excludeCiphers);
        }
        String[] includeCiphers = servlet.getConfiguration().getStrings(REST_SSL_INCLUDE_CIPHER_SUITES, ArrayUtils.EMPTY_STRING_ARRAY);
        if (includeCiphers.length != 0) {
            sslCtxFactory.setIncludeCipherSuites(includeCiphers);
        }
        String[] excludeProtocols = servlet.getConfiguration().getStrings(REST_SSL_EXCLUDE_PROTOCOLS, ArrayUtils.EMPTY_STRING_ARRAY);
        if (excludeProtocols.length != 0) {
            sslCtxFactory.setExcludeProtocols(excludeProtocols);
        }
        String[] includeProtocols = servlet.getConfiguration().getStrings(REST_SSL_INCLUDE_PROTOCOLS, ArrayUtils.EMPTY_STRING_ARRAY);
        if (includeProtocols.length != 0) {
            sslCtxFactory.setIncludeProtocols(includeProtocols);
        }
        serverConnector = new ServerConnector(server, new SslConnectionFactory(sslCtxFactory, HttpVersion.HTTP_1_1.toString()), new HttpConnectionFactory(httpsConfig));
    } else {
        serverConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
    }
    int acceptQueueSize = servlet.getConfiguration().getInt(REST_CONNECTOR_ACCEPT_QUEUE_SIZE, -1);
    if (acceptQueueSize >= 0) {
        serverConnector.setAcceptQueueSize(acceptQueueSize);
    }
    serverConnector.setPort(servicePort);
    serverConnector.setHost(host);
    server.addConnector(serverConnector);
    server.setStopAtShutdown(true);
    // set up context
    ServletContextHandler ctxHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    ctxHandler.addServlet(sh, PATH_SPEC_ANY);
    if (authFilter != null) {
        ctxHandler.addFilter(authFilter, PATH_SPEC_ANY, EnumSet.of(DispatcherType.REQUEST));
    }
    // Load filters from configuration.
    String[] filterClasses = servlet.getConfiguration().getStrings(FILTER_CLASSES, ArrayUtils.EMPTY_STRING_ARRAY);
    for (String filter : filterClasses) {
        filter = filter.trim();
        ctxHandler.addFilter(filter, PATH_SPEC_ANY, EnumSet.of(DispatcherType.REQUEST));
    }
    addCSRFFilter(ctxHandler, conf);
    HttpServerUtil.constrainHttpMethods(ctxHandler);
    // Put up info server.
    int port = conf.getInt("hbase.rest.info.port", 8085);
    if (port >= 0) {
        conf.setLong("startcode", System.currentTimeMillis());
        String a = conf.get("hbase.rest.info.bindAddress", "0.0.0.0");
        InfoServer infoServer = new InfoServer("rest", a, port, false, conf);
        infoServer.setAttribute("hbase.conf", conf);
        infoServer.start();
    }
    // start server
    server.start();
    server.join();
    LOG.info("***** STOPPING service '" + RESTServer.class.getSimpleName() + "' *****");
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) Configuration(org.apache.hadoop.conf.Configuration) HBaseConfiguration(org.apache.hadoop.hbase.HBaseConfiguration) InfoServer(org.apache.hadoop.hbase.http.InfoServer) Server(org.eclipse.jetty.server.Server) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) UserProvider(org.apache.hadoop.hbase.security.UserProvider) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) MBeanContainer(org.eclipse.jetty.jmx.MBeanContainer) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) InfoServer(org.apache.hadoop.hbase.http.InfoServer) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 44 with FilterHolder

use of org.eclipse.jetty.servlet.FilterHolder in project hbase by apache.

the class RESTServer method loginServerPrincipal.

// login the server principal (if using secure Hadoop)
private static Pair<FilterHolder, Class<? extends ServletContainer>> loginServerPrincipal(UserProvider userProvider, Configuration conf) throws Exception {
    Class<? extends ServletContainer> containerClass = ServletContainer.class;
    if (userProvider.isHadoopSecurityEnabled() && userProvider.isHBaseSecurityEnabled()) {
        String machineName = Strings.domainNamePointerToHostName(DNS.getDefaultHost(conf.get(REST_DNS_INTERFACE, "default"), conf.get(REST_DNS_NAMESERVER, "default")));
        String keytabFilename = conf.get(REST_KEYTAB_FILE);
        Preconditions.checkArgument(keytabFilename != null && !keytabFilename.isEmpty(), REST_KEYTAB_FILE + " should be set if security is enabled");
        String principalConfig = conf.get(REST_KERBEROS_PRINCIPAL);
        Preconditions.checkArgument(principalConfig != null && !principalConfig.isEmpty(), REST_KERBEROS_PRINCIPAL + " should be set if security is enabled");
        userProvider.login(REST_KEYTAB_FILE, REST_KERBEROS_PRINCIPAL, machineName);
        if (conf.get(REST_AUTHENTICATION_TYPE) != null) {
            containerClass = RESTServletContainer.class;
            FilterHolder authFilter = new FilterHolder();
            authFilter.setClassName(AuthFilter.class.getName());
            authFilter.setName("AuthenticationFilter");
            return new Pair<>(authFilter, containerClass);
        }
    }
    return new Pair<>(null, containerClass);
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) AuthFilter(org.apache.hadoop.hbase.rest.filter.AuthFilter) Pair(org.apache.hadoop.hbase.util.Pair)

Example 45 with FilterHolder

use of org.eclipse.jetty.servlet.FilterHolder in project hbase by apache.

the class RESTServer method addCSRFFilter.

static void addCSRFFilter(ServletContextHandler ctxHandler, Configuration conf) {
    restCSRFEnabled = conf.getBoolean(REST_CSRF_ENABLED_KEY, REST_CSRF_ENABLED_DEFAULT);
    if (restCSRFEnabled) {
        Set<String> restCsrfMethodsToIgnore = new HashSet<>();
        restCsrfMethodsToIgnore.addAll(getTrimmedStringList(conf, REST_CSRF_METHODS_TO_IGNORE_KEY, REST_CSRF_METHODS_TO_IGNORE_DEFAULT));
        Map<String, String> restCsrfParams = RestCsrfPreventionFilter.getFilterParams(conf, "hbase.rest-csrf.");
        FilterHolder holder = new FilterHolder();
        holder.setName("csrf");
        holder.setClassName(RestCsrfPreventionFilter.class.getName());
        holder.setInitParameters(restCsrfParams);
        ctxHandler.addFilter(holder, PATH_SPEC_ANY, EnumSet.allOf(DispatcherType.class));
    }
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) DispatcherType(javax.servlet.DispatcherType) HashSet(java.util.HashSet) RestCsrfPreventionFilter(org.apache.hadoop.hbase.rest.filter.RestCsrfPreventionFilter)

Aggregations

FilterHolder (org.eclipse.jetty.servlet.FilterHolder)84 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)44 Test (org.junit.Test)35 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)32 Server (org.eclipse.jetty.server.Server)21 CountDownLatch (java.util.concurrent.CountDownLatch)18 Filter (javax.servlet.Filter)11 IOException (java.io.IOException)10 URL (java.net.URL)10 DispatcherType (javax.servlet.DispatcherType)9 ServletException (javax.servlet.ServletException)8 AuthenticationToken (org.apache.hadoop.security.authentication.server.AuthenticationToken)8 ServerConnector (org.eclipse.jetty.server.ServerConnector)8 File (java.io.File)7 HttpURLConnection (java.net.HttpURLConnection)7 PrivilegedActionException (java.security.PrivilegedActionException)7 AuthenticationException (org.apache.hadoop.security.authentication.client.AuthenticationException)7 FilterMapping (org.eclipse.jetty.servlet.FilterMapping)7 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)7 List (java.util.List)6