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);
}
}
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);
}
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);
}
}
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);
}
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();
}
}
Aggregations