Search in sources :

Example 1 with TProcessorFactory

use of org.apache.thrift.TProcessorFactory 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 TProcessorFactory

use of org.apache.thrift.TProcessorFactory in project accumulo by apache.

the class TServerUtils method createNonBlockingServer.

/**
 * Create a NonBlockingServer with a custom thread pool that can dynamically resize itself.
 */
public static ServerAddress createNonBlockingServer(HostAndPort address, TProcessor processor, TProtocolFactory protocolFactory, final String serverName, String threadName, final int numThreads, final int numSTThreads, long timeBetweenThreadChecks, long maxMessageSize) throws TTransportException {
    final TNonblockingServerSocket transport = new TNonblockingServerSocket(new InetSocketAddress(address.getHost(), address.getPort()));
    final CustomNonBlockingServer.Args options = new CustomNonBlockingServer.Args(transport);
    options.protocolFactory(protocolFactory);
    options.transportFactory(ThriftUtil.transportFactory(maxMessageSize));
    options.maxReadBufferBytes = maxMessageSize;
    options.stopTimeoutVal(5);
    // Create our own very special thread pool.
    ThreadPoolExecutor pool = createSelfResizingThreadPool(serverName, numThreads, numSTThreads, timeBetweenThreadChecks);
    options.executorService(pool);
    options.processorFactory(new TProcessorFactory(processor));
    if (address.getPort() == 0) {
        address = HostAndPort.fromParts(address.getHost(), transport.getPort());
    }
    return new ServerAddress(new CustomNonBlockingServer(options), address);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) TNonblockingServerSocket(org.apache.thrift.transport.TNonblockingServerSocket) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) TProcessorFactory(org.apache.thrift.TProcessorFactory)

Example 3 with TProcessorFactory

use of org.apache.thrift.TProcessorFactory in project hive by apache.

the class ThriftBinaryCLIService method initServer.

@Override
protected void initServer() {
    try {
        // Server thread pool
        String threadPoolName = "HiveServer2-Handler-Pool";
        ExecutorService executorService = new ThreadPoolExecutor(minWorkerThreads, maxWorkerThreads, workerKeepAliveTime, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadFactoryWithGarbageCleanup(threadPoolName));
        // 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);
            String keyStoreType = hiveConf.getVar(ConfVars.HIVE_SERVER2_SSL_KEYSTORE_TYPE).trim();
            String keyStoreAlgorithm = hiveConf.getVar(ConfVars.HIVE_SERVER2_SSL_KEYMANAGERFACTORY_ALGORITHM).trim();
            String includeCiphersuites = hiveConf.getVar(ConfVars.HIVE_SERVER2_SSL_BINARY_INCLUDE_CIPHERSUITES).trim();
            serverSocket = HiveAuthUtils.getServerSSLSocket(hiveHost, portNum, keyStorePath, keyStorePassword, keyStoreType, keyStoreAlgorithm, sslVersionBlacklist, includeCiphersuites);
        }
        // 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)).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) {
                    metrics.incrementCounter(MetricsConstant.OPEN_CONNECTIONS);
                    metrics.incrementCounter(MetricsConstant.CUMULATIVE_CONNECTION_COUNT);
                }
                return new ThriftCLIServerContext();
            }

            /**
             * This is called by the Thrift server when the underlying client
             * connection is cleaned up by the server because the connection has
             * been closed.
             */
            @Override
            public void deleteContext(ServerContext serverContext, TProtocol input, TProtocol output) {
                Metrics metrics = MetricsFactory.getInstance();
                if (metrics != null) {
                    metrics.decrementCounter(MetricsConstant.OPEN_CONNECTIONS);
                }
                final ThriftCLIServerContext context = (ThriftCLIServerContext) serverContext;
                final Optional<SessionHandle> sessionHandle = context.getSessionHandle();
                if (sessionHandle.isPresent()) {
                    // Normally, the client should politely inform the server it is
                    // closing its session with Hive before closing its network
                    // connection. However, if the client connection dies for any reason
                    // (load-balancer round-robin configuration, firewall kills
                    // long-running sessions, bad client, failed client, timed-out
                    // client, etc.) then the server will close the connection without
                    // having properly cleaned up the Hive session (resources,
                    // configuration, logging etc.). That needs to be cleaned up now.
                    LOG.warn("Client connection bound to {} unexpectedly closed: closing this Hive session to release its resources. " + "The connection processed {} total messages during its lifetime of {}ms. Inspect the client connection " + "for time-out, firewall killing the connection, invalid load balancer configuration, etc.", sessionHandle, context.getMessagesProcessedCount(), context.getDuration().toMillis());
                    try {
                        final boolean close = cliService.getSessionManager().getSession(sessionHandle.get()).getHiveConf().getBoolVar(ConfVars.HIVE_SERVER2_CLOSE_SESSION_ON_DISCONNECT);
                        if (close) {
                            cliService.closeSession(sessionHandle.get());
                        } else {
                            LOG.warn("Session not actually closed because configuration {} is set to false", ConfVars.HIVE_SERVER2_CLOSE_SESSION_ON_DISCONNECT.varname);
                        }
                    } catch (HiveSQLException e) {
                        LOG.warn("Failed to close session", e);
                    }
                } else {
                    // able to create one in the first place
                    if (context.getSessionCount() == 0) {
                        LOG.info("A client connection was closed before creating a Hive session. " + "Most likely it is a client that is connecting to this server then " + "immediately closing the socket (i.e., TCP health check or port scanner)");
                    }
                }
            }

            @Override
            public void preServe() {
            }

            @Override
            public void processContext(ServerContext serverContext, TTransport input, TTransport output) {
                ThriftCLIServerContext context = (ThriftCLIServerContext) serverContext;
                currentServerContext.set(context);
                context.incMessagesProcessedCount();
            }
        });
        String msg = "Starting " + ThriftBinaryCLIService.class.getSimpleName() + " on port " + portNum + " with " + minWorkerThreads + "..." + maxWorkerThreads + " worker threads";
        LOG.info(msg);
    } catch (Exception e) {
        throw new RuntimeException("Failed to init thrift server", e);
    }
}
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) Optional(java.util.Optional) HiveSQLException(org.apache.hive.service.cli.HiveSQLException) 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) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) TTransport(org.apache.thrift.transport.TTransport) TThreadPoolServer(org.apache.thrift.server.TThreadPoolServer)

Example 4 with TProcessorFactory

use of org.apache.thrift.TProcessorFactory in project hive by apache.

the class TestPlainSaslHelper method testDoAsSetting.

/**
 * Test setting {@link HiveConf.ConfVars}} config parameter
 *   HIVE_SERVER2_ENABLE_DOAS for unsecure mode
 */
@Test
public void testDoAsSetting() {
    HiveConf hconf = new HiveConf();
    hconf.setVar(HiveConf.ConfVars.HIVE_AUTHORIZATION_MANAGER, "org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd.SQLStdHiveAuthorizerFactory");
    assertTrue("default value of hive server2 doAs should be true", hconf.getBoolVar(ConfVars.HIVE_SERVER2_ENABLE_DOAS));
    CLIService cliService = new CLIService(null, true);
    cliService.init(hconf);
    ThriftCLIService tcliService = new ThriftBinaryCLIService(cliService);
    tcliService.init(hconf);
    TProcessorFactory procFactory = PlainSaslHelper.getPlainProcessorFactory(tcliService);
    assertEquals("doAs enabled processor for unsecure mode", procFactory.getProcessor(null).getClass(), TSetIpAddressProcessor.class);
}
Also used : ThriftBinaryCLIService(org.apache.hive.service.cli.thrift.ThriftBinaryCLIService) ThriftCLIService(org.apache.hive.service.cli.thrift.ThriftCLIService) HiveConf(org.apache.hadoop.hive.conf.HiveConf) ThriftCLIService(org.apache.hive.service.cli.thrift.ThriftCLIService) CLIService(org.apache.hive.service.cli.CLIService) ThriftBinaryCLIService(org.apache.hive.service.cli.thrift.ThriftBinaryCLIService) TProcessorFactory(org.apache.thrift.TProcessorFactory) Test(org.junit.Test)

Example 5 with TProcessorFactory

use of org.apache.thrift.TProcessorFactory in project tech by ffyyhh995511.

the class Test3 method main.

public static void main(String[] args2) {
    try {
        // 非阻塞式的,配合TFramedTransport使用
        TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(7911);
        // 关联处理器与Service服务的实现
        TProcessor processor = new Hello.Processor<Hello.Iface>(new HelloImpl());
        // 目前Thrift提供的最高级的模式,可并发处理客户端请求
        TThreadedSelectorServer.Args args = new TThreadedSelectorServer.Args(serverTransport);
        args.processor(processor);
        // 设置协议工厂,高效率的、密集的二进制编码格式进行数据传输协议
        args.protocolFactory(new TCompactProtocol.Factory());
        // 设置传输工厂,使用非阻塞方式,按块的大小进行传输,类似于Java中的NIO
        args.transportFactory(new TFramedTransport.Factory());
        // 设置处理器工厂,只返回一个单例实例
        args.processorFactory(new TProcessorFactory(processor));
        // 多个线程,主要负责客户端的IO处理
        args.selectorThreads(2);
        // 工作线程池
        ExecutorService pool = Executors.newFixedThreadPool(3);
        args.executorService(pool);
        TThreadedSelectorServer server = new TThreadedSelectorServer(args);
        System.out.println("Starting server on port " + 7911 + "......");
        server.serve();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : TNonblockingServerTransport(org.apache.thrift.transport.TNonblockingServerTransport) TProcessor(org.apache.thrift.TProcessor) TThreadedSelectorServer(org.apache.thrift.server.TThreadedSelectorServer) TCompactProtocol(org.apache.thrift.protocol.TCompactProtocol) TProcessorFactory(org.apache.thrift.TProcessorFactory) HelloImpl(org.tech.model.impl.HelloImpl) TProcessor(org.apache.thrift.TProcessor) Hello(org.tech.model.Hello) TFramedTransport(org.apache.thrift.transport.TFramedTransport) TNonblockingServerSocket(org.apache.thrift.transport.TNonblockingServerSocket) ExecutorService(java.util.concurrent.ExecutorService)

Aggregations

TProcessorFactory (org.apache.thrift.TProcessorFactory)5 ExecutorService (java.util.concurrent.ExecutorService)3 ArrayList (java.util.ArrayList)2 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)2 Metrics (org.apache.hadoop.hive.common.metrics.common.Metrics)2 MetricsFactory (org.apache.hadoop.hive.common.metrics.common.MetricsFactory)2 HiveAuthFactory (org.apache.hive.service.auth.HiveAuthFactory)2 HiveSQLException (org.apache.hive.service.cli.HiveSQLException)2 ThreadFactoryWithGarbageCleanup (org.apache.hive.service.server.ThreadFactoryWithGarbageCleanup)2 TBinaryProtocol (org.apache.thrift.protocol.TBinaryProtocol)2 TProtocol (org.apache.thrift.protocol.TProtocol)2 ServerContext (org.apache.thrift.server.ServerContext)2 TServerEventHandler (org.apache.thrift.server.TServerEventHandler)2 TThreadPoolServer (org.apache.thrift.server.TThreadPoolServer)2 TNonblockingServerSocket (org.apache.thrift.transport.TNonblockingServerSocket)2 TServerSocket (org.apache.thrift.transport.TServerSocket)2 TTransport (org.apache.thrift.transport.TTransport)2 TTransportFactory (org.apache.thrift.transport.TTransportFactory)2 InetSocketAddress (java.net.InetSocketAddress)1 Optional (java.util.Optional)1