Search in sources :

Example 1 with TTransportFactory

use of org.apache.thrift.transport.TTransportFactory in project hive by apache.

the class ThriftBinaryCLIService method run.

@Override
public void run() {
    try {
        // Server thread pool
        String threadPoolName = "HiveServer2-Handler-Pool";
        ExecutorService executorService = new ThreadPoolExecutorWithOomHook(minWorkerThreads, maxWorkerThreads, workerKeepAliveTime, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactoryWithGarbageCleanup(threadPoolName), oomHook);
        // Thrift configs
        hiveAuthFactory = new HiveAuthFactory(hiveConf);
        TTransportFactory transportFactory = hiveAuthFactory.getAuthTransFactory();
        TProcessorFactory processorFactory = hiveAuthFactory.getAuthProcFactory(this);
        TServerSocket serverSocket = null;
        List<String> sslVersionBlacklist = new ArrayList<String>();
        for (String sslVersion : hiveConf.getVar(ConfVars.HIVE_SSL_PROTOCOL_BLACKLIST).split(",")) {
            sslVersionBlacklist.add(sslVersion);
        }
        if (!hiveConf.getBoolVar(ConfVars.HIVE_SERVER2_USE_SSL)) {
            serverSocket = HiveAuthUtils.getServerSocket(hiveHost, portNum);
        } else {
            String keyStorePath = hiveConf.getVar(ConfVars.HIVE_SERVER2_SSL_KEYSTORE_PATH).trim();
            if (keyStorePath.isEmpty()) {
                throw new IllegalArgumentException(ConfVars.HIVE_SERVER2_SSL_KEYSTORE_PATH.varname + " Not configured for SSL connection");
            }
            String keyStorePassword = ShimLoader.getHadoopShims().getPassword(hiveConf, HiveConf.ConfVars.HIVE_SERVER2_SSL_KEYSTORE_PASSWORD.varname);
            serverSocket = HiveAuthUtils.getServerSSLSocket(hiveHost, portNum, keyStorePath, keyStorePassword, sslVersionBlacklist);
        }
        // Server args
        int maxMessageSize = hiveConf.getIntVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_MAX_MESSAGE_SIZE);
        int requestTimeout = (int) hiveConf.getTimeVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_LOGIN_TIMEOUT, TimeUnit.SECONDS);
        int beBackoffSlotLength = (int) hiveConf.getTimeVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_LOGIN_BEBACKOFF_SLOT_LENGTH, TimeUnit.MILLISECONDS);
        TThreadPoolServer.Args sargs = new TThreadPoolServer.Args(serverSocket).processorFactory(processorFactory).transportFactory(transportFactory).protocolFactory(new TBinaryProtocol.Factory()).inputProtocolFactory(new TBinaryProtocol.Factory(true, true, maxMessageSize, maxMessageSize)).requestTimeout(requestTimeout).requestTimeoutUnit(TimeUnit.SECONDS).beBackoffSlotLength(beBackoffSlotLength).beBackoffSlotLengthUnit(TimeUnit.MILLISECONDS).executorService(executorService);
        // TCP Server
        server = new TThreadPoolServer(sargs);
        server.setServerEventHandler(new TServerEventHandler() {

            @Override
            public ServerContext createContext(TProtocol input, TProtocol output) {
                Metrics metrics = MetricsFactory.getInstance();
                if (metrics != null) {
                    try {
                        metrics.incrementCounter(MetricsConstant.OPEN_CONNECTIONS);
                        metrics.incrementCounter(MetricsConstant.CUMULATIVE_CONNECTION_COUNT);
                    } catch (Exception e) {
                        LOG.warn("Error Reporting JDO operation to Metrics system", e);
                    }
                }
                return new ThriftCLIServerContext();
            }

            @Override
            public void deleteContext(ServerContext serverContext, TProtocol input, TProtocol output) {
                Metrics metrics = MetricsFactory.getInstance();
                if (metrics != null) {
                    try {
                        metrics.decrementCounter(MetricsConstant.OPEN_CONNECTIONS);
                    } catch (Exception e) {
                        LOG.warn("Error Reporting JDO operation to Metrics system", e);
                    }
                }
                ThriftCLIServerContext context = (ThriftCLIServerContext) serverContext;
                SessionHandle sessionHandle = context.getSessionHandle();
                if (sessionHandle != null) {
                    LOG.info("Session disconnected without closing properly. ");
                    try {
                        boolean close = cliService.getSessionManager().getSession(sessionHandle).getHiveConf().getBoolVar(ConfVars.HIVE_SERVER2_CLOSE_SESSION_ON_DISCONNECT);
                        LOG.info((close ? "" : "Not ") + "Closing the session: " + sessionHandle);
                        if (close) {
                            cliService.closeSession(sessionHandle);
                        }
                    } catch (HiveSQLException e) {
                        LOG.warn("Failed to close session: " + e, e);
                    }
                }
            }

            @Override
            public void preServe() {
            }

            @Override
            public void processContext(ServerContext serverContext, TTransport input, TTransport output) {
                currentServerContext.set(serverContext);
            }
        });
        String msg = "Starting " + ThriftBinaryCLIService.class.getSimpleName() + " on port " + portNum + " with " + minWorkerThreads + "..." + maxWorkerThreads + " worker threads";
        LOG.info(msg);
        server.serve();
    } catch (Throwable t) {
        LOG.error("Error starting HiveServer2: could not start " + ThriftBinaryCLIService.class.getSimpleName(), t);
        System.exit(-1);
    }
}
Also used : ThreadFactoryWithGarbageCleanup(org.apache.hive.service.server.ThreadFactoryWithGarbageCleanup) TServerEventHandler(org.apache.thrift.server.TServerEventHandler) ArrayList(java.util.ArrayList) HiveAuthFactory(org.apache.hive.service.auth.HiveAuthFactory) TProcessorFactory(org.apache.thrift.TProcessorFactory) MetricsFactory(org.apache.hadoop.hive.common.metrics.common.MetricsFactory) TTransportFactory(org.apache.thrift.transport.TTransportFactory) TProcessorFactory(org.apache.thrift.TProcessorFactory) TServerSocket(org.apache.thrift.transport.TServerSocket) Metrics(org.apache.hadoop.hive.common.metrics.common.Metrics) TProtocol(org.apache.thrift.protocol.TProtocol) HiveSQLException(org.apache.hive.service.cli.HiveSQLException) SessionHandle(org.apache.hive.service.cli.SessionHandle) TTransportFactory(org.apache.thrift.transport.TTransportFactory) HiveSQLException(org.apache.hive.service.cli.HiveSQLException) TBinaryProtocol(org.apache.thrift.protocol.TBinaryProtocol) ServerContext(org.apache.thrift.server.ServerContext) ExecutorService(java.util.concurrent.ExecutorService) HiveAuthFactory(org.apache.hive.service.auth.HiveAuthFactory) TTransport(org.apache.thrift.transport.TTransport) TThreadPoolServer(org.apache.thrift.server.TThreadPoolServer)

Example 2 with TTransportFactory

use of org.apache.thrift.transport.TTransportFactory in project hbase by apache.

the class ThriftServerRunner method setupServer.

/**
   * Setting up the thrift TServer
   */
private void setupServer() throws Exception {
    // Construct correct ProtocolFactory
    TProtocolFactory protocolFactory;
    if (conf.getBoolean(COMPACT_CONF_KEY, false)) {
        LOG.debug("Using compact protocol");
        protocolFactory = new TCompactProtocol.Factory();
    } else {
        LOG.debug("Using binary protocol");
        protocolFactory = new TBinaryProtocol.Factory();
    }
    final TProcessor p = new Hbase.Processor<>(handler);
    ImplType implType = ImplType.getServerImpl(conf);
    TProcessor processor = p;
    // Construct correct TransportFactory
    TTransportFactory transportFactory;
    if (conf.getBoolean(FRAMED_CONF_KEY, false) || implType.isAlwaysFramed) {
        if (qop != null) {
            throw new RuntimeException("Thrift server authentication" + " doesn't work with framed transport yet");
        }
        transportFactory = new TFramedTransport.Factory(conf.getInt(MAX_FRAME_SIZE_CONF_KEY, 2) * 1024 * 1024);
        LOG.debug("Using framed transport");
    } else if (qop == null) {
        transportFactory = new TTransportFactory();
    } else {
        // Extract the name from the principal
        String name = SecurityUtil.getUserFromPrincipal(conf.get("hbase.thrift.kerberos.principal"));
        Map<String, String> saslProperties = new HashMap<>();
        saslProperties.put(Sasl.QOP, qop);
        TSaslServerTransport.Factory saslFactory = new TSaslServerTransport.Factory();
        saslFactory.addServerDefinition("GSSAPI", name, host, saslProperties, new SaslGssCallbackHandler() {

            @Override
            public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
                AuthorizeCallback ac = null;
                for (Callback callback : callbacks) {
                    if (callback instanceof AuthorizeCallback) {
                        ac = (AuthorizeCallback) callback;
                    } else {
                        throw new UnsupportedCallbackException(callback, "Unrecognized SASL GSSAPI Callback");
                    }
                }
                if (ac != null) {
                    String authid = ac.getAuthenticationID();
                    String authzid = ac.getAuthorizationID();
                    if (!authid.equals(authzid)) {
                        ac.setAuthorized(false);
                    } else {
                        ac.setAuthorized(true);
                        String userName = SecurityUtil.getUserFromPrincipal(authzid);
                        LOG.info("Effective user: " + userName);
                        ac.setAuthorizedID(userName);
                    }
                }
            }
        });
        transportFactory = saslFactory;
        // Create a processor wrapper, to get the caller
        processor = new TProcessor() {

            @Override
            public boolean process(TProtocol inProt, TProtocol outProt) throws TException {
                TSaslServerTransport saslServerTransport = (TSaslServerTransport) inProt.getTransport();
                SaslServer saslServer = saslServerTransport.getSaslServer();
                String principal = saslServer.getAuthorizationID();
                hbaseHandler.setEffectiveUser(principal);
                return p.process(inProt, outProt);
            }
        };
    }
    if (conf.get(BIND_CONF_KEY) != null && !implType.canSpecifyBindIP) {
        LOG.error("Server types " + Joiner.on(", ").join(ImplType.serversThatCannotSpecifyBindIP()) + " don't support IP " + "address binding at the moment. See " + "https://issues.apache.org/jira/browse/HBASE-2155 for details.");
        throw new RuntimeException("-" + BIND_CONF_KEY + " not supported with " + implType);
    }
    // Thrift's implementation uses '0' as a placeholder for 'use the default.'
    int backlog = conf.getInt(BACKLOG_CONF_KEY, 0);
    if (implType == ImplType.HS_HA || implType == ImplType.NONBLOCKING || implType == ImplType.THREADED_SELECTOR) {
        InetAddress listenAddress = getBindAddress(conf);
        TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(new InetSocketAddress(listenAddress, listenPort));
        if (implType == ImplType.NONBLOCKING) {
            TNonblockingServer.Args serverArgs = new TNonblockingServer.Args(serverTransport);
            serverArgs.processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory);
            tserver = new TNonblockingServer(serverArgs);
        } else if (implType == ImplType.HS_HA) {
            THsHaServer.Args serverArgs = new THsHaServer.Args(serverTransport);
            CallQueue callQueue = new CallQueue(new LinkedBlockingQueue<>(), metrics);
            ExecutorService executorService = createExecutor(callQueue, serverArgs.getMaxWorkerThreads(), serverArgs.getMaxWorkerThreads());
            serverArgs.executorService(executorService).processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory);
            tserver = new THsHaServer(serverArgs);
        } else {
            // THREADED_SELECTOR
            TThreadedSelectorServer.Args serverArgs = new HThreadedSelectorServerArgs(serverTransport, conf);
            CallQueue callQueue = new CallQueue(new LinkedBlockingQueue<>(), metrics);
            ExecutorService executorService = createExecutor(callQueue, serverArgs.getWorkerThreads(), serverArgs.getWorkerThreads());
            serverArgs.executorService(executorService).processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory);
            tserver = new TThreadedSelectorServer(serverArgs);
        }
        LOG.info("starting HBase " + implType.simpleClassName() + " server on " + Integer.toString(listenPort));
    } else if (implType == ImplType.THREAD_POOL) {
        // Thread pool server. Get the IP address to bind to.
        InetAddress listenAddress = getBindAddress(conf);
        int readTimeout = conf.getInt(THRIFT_SERVER_SOCKET_READ_TIMEOUT_KEY, THRIFT_SERVER_SOCKET_READ_TIMEOUT_DEFAULT);
        TServerTransport serverTransport = new TServerSocket(new TServerSocket.ServerSocketTransportArgs().bindAddr(new InetSocketAddress(listenAddress, listenPort)).backlog(backlog).clientTimeout(readTimeout));
        TBoundedThreadPoolServer.Args serverArgs = new TBoundedThreadPoolServer.Args(serverTransport, conf);
        serverArgs.processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory);
        LOG.info("starting " + ImplType.THREAD_POOL.simpleClassName() + " on " + listenAddress + ":" + Integer.toString(listenPort) + " with readTimeout " + readTimeout + "ms; " + serverArgs);
        TBoundedThreadPoolServer tserver = new TBoundedThreadPoolServer(serverArgs, metrics);
        this.tserver = tserver;
    } else {
        throw new AssertionError("Unsupported Thrift server implementation: " + implType.simpleClassName());
    }
    // A sanity check that we instantiated the right type of server.
    if (tserver.getClass() != implType.serverClass) {
        throw new AssertionError("Expected to create Thrift server class " + implType.serverClass.getName() + " but got " + tserver.getClass().getName());
    }
    registerFilters(conf);
}
Also used : TProtocolFactory(org.apache.thrift.protocol.TProtocolFactory) TNonblockingServerTransport(org.apache.thrift.transport.TNonblockingServerTransport) TProcessor(org.apache.thrift.TProcessor) SaslServer(javax.security.sasl.SaslServer) InetSocketAddress(java.net.InetSocketAddress) TThreadedSelectorServer(org.apache.thrift.server.TThreadedSelectorServer) LogFactory(org.apache.commons.logging.LogFactory) TProtocolFactory(org.apache.thrift.protocol.TProtocolFactory) TTransportFactory(org.apache.thrift.transport.TTransportFactory) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) TCompactProtocol(org.apache.thrift.protocol.TCompactProtocol) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) AuthorizeCallback(javax.security.sasl.AuthorizeCallback) TServerSocket(org.apache.thrift.transport.TServerSocket) THsHaServer(org.apache.thrift.server.THsHaServer) TProcessor(org.apache.thrift.TProcessor) TProtocol(org.apache.thrift.protocol.TProtocol) TFramedTransport(org.apache.thrift.transport.TFramedTransport) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) TTransportFactory(org.apache.thrift.transport.TTransportFactory) TNonblockingServer(org.apache.thrift.server.TNonblockingServer) TServerTransport(org.apache.thrift.transport.TServerTransport) TSaslServerTransport(org.apache.thrift.transport.TSaslServerTransport) SaslGssCallbackHandler(org.apache.hadoop.security.SaslRpcServer.SaslGssCallbackHandler) Callback(javax.security.auth.callback.Callback) AuthorizeCallback(javax.security.sasl.AuthorizeCallback) TBinaryProtocol(org.apache.thrift.protocol.TBinaryProtocol) TNonblockingServerSocket(org.apache.thrift.transport.TNonblockingServerSocket) ExecutorService(java.util.concurrent.ExecutorService) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) InetAddress(java.net.InetAddress)

Example 3 with TTransportFactory

use of org.apache.thrift.transport.TTransportFactory in project hbase by apache.

the class ThriftServer method getTTransportFactory.

private static TTransportFactory getTTransportFactory(SaslUtil.QualityOfProtection qop, String name, String host, boolean framed, int frameSize) {
    if (framed) {
        if (qop != null) {
            throw new RuntimeException("Thrift server authentication" + " doesn't work with framed transport yet");
        }
        log.debug("Using framed transport");
        return new TFramedTransport.Factory(frameSize);
    } else if (qop == null) {
        return new TTransportFactory();
    } else {
        Map<String, String> saslProperties = new HashMap<>();
        saslProperties.put(Sasl.QOP, qop.getSaslQop());
        TSaslServerTransport.Factory saslFactory = new TSaslServerTransport.Factory();
        saslFactory.addServerDefinition("GSSAPI", name, host, saslProperties, new SaslGssCallbackHandler() {

            @Override
            public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
                AuthorizeCallback ac = null;
                for (Callback callback : callbacks) {
                    if (callback instanceof AuthorizeCallback) {
                        ac = (AuthorizeCallback) callback;
                    } else {
                        throw new UnsupportedCallbackException(callback, "Unrecognized SASL GSSAPI Callback");
                    }
                }
                if (ac != null) {
                    String authid = ac.getAuthenticationID();
                    String authzid = ac.getAuthorizationID();
                    if (!authid.equals(authzid)) {
                        ac.setAuthorized(false);
                    } else {
                        ac.setAuthorized(true);
                        String userName = SecurityUtil.getUserFromPrincipal(authzid);
                        log.info("Effective user: " + userName);
                        ac.setAuthorizedID(userName);
                    }
                }
            }
        });
        return saslFactory;
    }
}
Also used : TSaslServerTransport(org.apache.thrift.transport.TSaslServerTransport) SaslGssCallbackHandler(org.apache.hadoop.security.SaslRpcServer.SaslGssCallbackHandler) AuthorizeCallback(javax.security.sasl.AuthorizeCallback) Callback(javax.security.auth.callback.Callback) LogFactory(org.apache.commons.logging.LogFactory) TTransportFactory(org.apache.thrift.transport.TTransportFactory) TProtocolFactory(org.apache.thrift.protocol.TProtocolFactory) TTransportFactory(org.apache.thrift.transport.TTransportFactory) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Map(java.util.Map) HashMap(java.util.HashMap) AuthorizeCallback(javax.security.sasl.AuthorizeCallback)

Example 4 with TTransportFactory

use of org.apache.thrift.transport.TTransportFactory in project storm by apache.

the class SaslTransportPlugin method getServer.

@Override
public TServer getServer(TProcessor processor) throws IOException, TTransportException {
    int port = type.getPort(storm_conf);
    Integer socketTimeout = type.getSocketTimeOut(storm_conf);
    TTransportFactory serverTransportFactory = getServerTransportFactory();
    TServerSocket serverTransport = null;
    if (socketTimeout != null) {
        serverTransport = new TServerSocket(port, socketTimeout);
    } else {
        serverTransport = new TServerSocket(port);
    }
    int numWorkerThreads = type.getNumThreads(storm_conf);
    Integer queueSize = type.getQueueSize(storm_conf);
    TThreadPoolServer.Args server_args = new TThreadPoolServer.Args(serverTransport).processor(new TUGIWrapProcessor(processor)).minWorkerThreads(numWorkerThreads).maxWorkerThreads(numWorkerThreads).protocolFactory(new TBinaryProtocol.Factory(false, true));
    if (serverTransportFactory != null) {
        server_args.transportFactory(serverTransportFactory);
    }
    BlockingQueue workQueue = new SynchronousQueue();
    if (queueSize != null) {
        workQueue = new ArrayBlockingQueue(queueSize);
    }
    ThreadPoolExecutor executorService = new ExtendedThreadPoolExecutor(numWorkerThreads, numWorkerThreads, 60, TimeUnit.SECONDS, workQueue);
    server_args.executorService(executorService);
    return new TThreadPoolServer(server_args);
}
Also used : BlockingQueue(java.util.concurrent.BlockingQueue) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) TTransportFactory(org.apache.thrift.transport.TTransportFactory) ExtendedThreadPoolExecutor(org.apache.storm.utils.ExtendedThreadPoolExecutor) TServerSocket(org.apache.thrift.transport.TServerSocket) TBinaryProtocol(org.apache.thrift.protocol.TBinaryProtocol) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) SynchronousQueue(java.util.concurrent.SynchronousQueue) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) ExtendedThreadPoolExecutor(org.apache.storm.utils.ExtendedThreadPoolExecutor) TThreadPoolServer(org.apache.thrift.server.TThreadPoolServer)

Example 5 with TTransportFactory

use of org.apache.thrift.transport.TTransportFactory in project storm by apache.

the class DigestSaslTransportPlugin method getServerTransportFactory.

protected TTransportFactory getServerTransportFactory() throws IOException {
    //create an authentication callback handler
    CallbackHandler serer_callback_handler = new ServerCallbackHandler(login_conf);
    //create a transport factory that will invoke our auth callback for digest
    TSaslServerTransport.Factory factory = new TSaslServerTransport.Factory();
    factory.addServerDefinition(DIGEST, AuthUtils.SERVICE, "localhost", null, serer_callback_handler);
    LOG.info("SASL DIGEST-MD5 transport factory will be used");
    return factory;
}
Also used : TSaslServerTransport(org.apache.thrift.transport.TSaslServerTransport) CallbackHandler(javax.security.auth.callback.CallbackHandler) LoggerFactory(org.slf4j.LoggerFactory) TTransportFactory(org.apache.thrift.transport.TTransportFactory)

Aggregations

TTransportFactory (org.apache.thrift.transport.TTransportFactory)16 TSaslServerTransport (org.apache.thrift.transport.TSaslServerTransport)9 TBinaryProtocol (org.apache.thrift.protocol.TBinaryProtocol)8 TThreadPoolServer (org.apache.thrift.server.TThreadPoolServer)7 LoggerFactory (org.slf4j.LoggerFactory)6 CallbackHandler (javax.security.auth.callback.CallbackHandler)5 TServerSocket (org.apache.thrift.transport.TServerSocket)5 IOException (java.io.IOException)4 TProtocol (org.apache.thrift.protocol.TProtocol)4 TProtocolFactory (org.apache.thrift.protocol.TProtocolFactory)4 HashMap (java.util.HashMap)3 TreeMap (java.util.TreeMap)3 LoginException (javax.security.auth.login.LoginException)3 InetSocketAddress (java.net.InetSocketAddress)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)2 BlockingQueue (java.util.concurrent.BlockingQueue)2 ExecutorService (java.util.concurrent.ExecutorService)2 SynchronousQueue (java.util.concurrent.SynchronousQueue)2