Example usage for org.apache.thrift.server TThreadPoolServer TThreadPoolServer

List of usage examples for org.apache.thrift.server TThreadPoolServer TThreadPoolServer

Introduction

In this page you can find the example usage for org.apache.thrift.server TThreadPoolServer TThreadPoolServer.

Prototype

public TThreadPoolServer(Args args) 

Source Link

Usage

From source file:com.skplanet.querycache.server.QueryCacheServer.java

License:Apache License

public static void secure(TCLIService.Processor processor) {
    try {//from w  w  w.  j a v a  2  s  . c  om
        /*
         * Use TSSLTransportParameters to setup the required SSL parameters. In this example
         * we are setting the keystore and the keystore password. Other things like algorithms,
         * cipher suites, client auth etc can be set. 
         */
        TSSLTransportParameters params = new TSSLTransportParameters();
        // The Keystore contains the private key
        params.setKeyStore("/home/leejy/work/thrift-0.9.1/lib/java/test/.keystore", "thrift", null, null);

        /*
         * Use any of the TSSLTransportFactory to get a server transport with the appropriate
         * SSL configuration. You can use the default settings if properties are set in the command line.
         * Ex: -Djavax.net.ssl.keyStore=.keystore and -Djavax.net.ssl.keyStorePassword=thrift
         * 
         * Note: You need not explicitly call open(). The underlying server socket is bound on return
         * from the factory class. 
         */
        TServerTransport serverTransport = TSSLTransportFactory.getServerSocket(2849, 0, null, params);
        //TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));

        // Use this for a multi threaded server
        TServer server = new TThreadPoolServer(
                new TThreadPoolServer.Args(serverTransport).processor(processor));

        System.out.println("Starting the secure server...");
        server.serve();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.sleepycat.server.config.BdbServerConfig.java

License:Open Source License

private TServer createSslServer(TProcessorFactory processor) throws TTransportException, UnknownHostException {
    TSSLTransportFactory.TSSLTransportParameters parameters = new TSSLTransportFactory.TSSLTransportParameters();

    if (!this.properties.getString(KEY_STORE, "").isEmpty()) {
        configureKeyStore(parameters);//from  w w w  .j  a  v  a 2  s  .  co  m
    }
    if (!this.properties.getString(TRUST_STORE, "").isEmpty()) {
        configureTrustStore(parameters);
    }

    TServerSocket socket = TSSLTransportFactory.getServerSocket(getPort(), 0,
            InetAddress.getByName(this.properties.getString(SSL_HOST, null)), parameters);
    TThreadPoolServer.Args args = new TThreadPoolServer.Args(socket);
    args.maxWorkerThreads(getWorkers()).minWorkerThreads(getWorkers());
    args.protocolFactory(new TCompactProtocol.Factory());
    args.processorFactory(processor);

    return new TThreadPoolServer(args);
}

From source file:com.twitter.aurora.scheduler.thrift.ThriftServer.java

License:Apache License

/**
 * Starts the server.// w  w  w.ja va 2  s  . com
 * This may be called at any point except when the server is already alive.  That is, it's
 * allowable to start, stop, and re-start the server.
 *
 * @param socket The socket to use.
 * @param processor The processor to handle requests.
 */
public synchronized void start(ServerSocket socket, TProcessor processor) {
    Preconditions.checkNotNull(socket);
    Preconditions.checkNotNull(processor);
    Preconditions.checkState(status != Status.ALIVE, "Server must only be started once.");
    setStatus(Status.ALIVE);
    TThreadPoolServer.Args args = new TThreadPoolServer.Args(new TServerSocket(socket)).processor(processor)
            .protocolFactory(new TBinaryProtocol.Factory(false, true));

    final TServer starting = new TThreadPoolServer(args);
    server = starting;
    LOG.info("Starting thrift server on port " + socket.getLocalPort());

    Thread listeningThread = new ThreadFactoryBuilder().setDaemon(false).build().newThread(new Runnable() {
        @Override
        public void run() {
            try {
                starting.serve();
            } catch (Throwable t) {
                LOG.log(Level.WARNING, "Uncaught exception while attempting to handle service requests: " + t,
                        t);
                setStatus(Status.DEAD);
            }
        }
    });

    listeningThread.start();
}

From source file:com.uber.hoodie.hive.util.HiveTestService.java

License:Apache License

public TServer startMetaStore(String forceBindIP, int port, HiveConf conf) throws IOException {
    try {/*from w ww  .j a  va2  s. c o m*/
        // Server will create new threads up to max as necessary. After an idle
        // period, it will destory threads to keep the number of threads in the
        // pool to min.
        int minWorkerThreads = conf.getIntVar(HiveConf.ConfVars.METASTORESERVERMINTHREADS);
        int maxWorkerThreads = conf.getIntVar(HiveConf.ConfVars.METASTORESERVERMAXTHREADS);
        boolean tcpKeepAlive = conf.getBoolVar(HiveConf.ConfVars.METASTORE_TCP_KEEP_ALIVE);
        boolean useFramedTransport = conf.getBoolVar(HiveConf.ConfVars.METASTORE_USE_THRIFT_FRAMED_TRANSPORT);

        // don't support SASL yet
        //boolean useSasl = conf.getBoolVar(HiveConf.ConfVars.METASTORE_USE_THRIFT_SASL);

        TServerTransport serverTransport;
        if (forceBindIP != null) {
            InetSocketAddress address = new InetSocketAddress(forceBindIP, port);
            serverTransport = tcpKeepAlive ? new TServerSocketKeepAlive(address) : new TServerSocket(address);

        } else {
            serverTransport = tcpKeepAlive ? new TServerSocketKeepAlive(port) : new TServerSocket(port);
        }

        TProcessor processor;
        TTransportFactory transFactory;

        IHMSHandler handler = (IHMSHandler) HiveMetaStore.newRetryingHMSHandler("new db based metaserver", conf,
                true);

        if (conf.getBoolVar(HiveConf.ConfVars.METASTORE_EXECUTE_SET_UGI)) {
            transFactory = useFramedTransport
                    ? new ChainedTTransportFactory(new TFramedTransport.Factory(),
                            new TUGIContainingTransport.Factory())
                    : new TUGIContainingTransport.Factory();

            processor = new TUGIBasedProcessor<IHMSHandler>(handler);
            LOG.info("Starting DB backed MetaStore Server with SetUGI enabled");
        } else {
            transFactory = useFramedTransport ? new TFramedTransport.Factory() : new TTransportFactory();
            processor = new TSetIpAddressProcessor<IHMSHandler>(handler);
            LOG.info("Starting DB backed MetaStore Server");
        }

        TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport).processor(processor)
                .transportFactory(transFactory).protocolFactory(new TBinaryProtocol.Factory())
                .minWorkerThreads(minWorkerThreads).maxWorkerThreads(maxWorkerThreads);

        final TServer tServer = new TThreadPoolServer(args);
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                tServer.serve();
            }
        });
        return tServer;
    } catch (Throwable x) {
        throw new IOException(x);
    }
}

From source file:com.vmware.photon.controller.chairman.ChairmanServer.java

License:Open Source License

public void serve() throws TTransportException, IOException {
    InetAddress registrationIpAddress = InetAddress.getByName(registrationAddress);
    if (registrationIpAddress.isAnyLocalAddress()) {
        logger.error("Using a wildcard registration address will not work with service registry: {}",
                registrationAddress);//  w ww . ja  v  a 2  s.c om
        throw new IllegalArgumentException("Wildcard registration address");
    }

    InetAddress bindIpAddress = InetAddress.getByName(bind);
    InetSocketAddress bindSocketAddress = new InetSocketAddress(bindIpAddress, port);
    TServerSocket transport = new TServerSocket(bindSocketAddress);

    Chairman.Processor<ChairmanService> chairmanProcessor = new Chairman.Processor<>(chairmanService);
    TMultiplexedProcessor processor = new TMultiplexedProcessor();
    processor.registerProcessor("Chairman", chairmanProcessor);

    // TODO(vspivak): add configurable executor
    server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).processor(processor)
            .protocolFactory(protocolFactory).transportFactory(transportFactory));

    // Need to re-fetch local port in case it was 0
    InetSocketAddress registrationSocketAddress = new InetSocketAddress(registrationIpAddress,
            transport.getServerSocket().getLocalPort());
    serviceNode = serviceNodeFactory.createLeader("chairman", registrationSocketAddress);

    ServiceNodeUtils.joinService(serviceNode, retryIntervalMsec, manager);

    logger.info("Starting chairman ({})", buildInfo);
    logger.info("Listening on: {}", bindSocketAddress);
    logger.info("Registering address: {}", registrationSocketAddress);
    server.serve();
}

From source file:com.vmware.photon.controller.common.thrift.EndToEndTest.java

License:Open Source License

@Test
public void testEndToEnd() throws TException, InterruptedException {
    TServerSocket transport = new TServerSocket(0);
    Echoer.Processor<EchoServer> processor = new Echoer.Processor<>(new EchoServer());
    server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).transportFactory(transportFactory)
            .protocolFactory(protocolFactory).processor(processor));

    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(new Runnable() {
        @Override/*w  w w  . j a v  a  2  s.  co  m*/
        public void run() {
            server.serve();
        }
    });

    InetSocketAddress localPort = new InetSocketAddress(transport.getServerSocket().getLocalPort());
    ClientPool<Echoer.AsyncClient> pool = poolFactory.create(new StaticServerSet(localPort),
            new ClientPoolOptions().setMaxClients(10).setMaxWaiters(10));
    ClientProxy<Echoer.AsyncClient> clientProxy = proxyFactory.create(pool);

    final CountDownLatch latch = new CountDownLatch(1);
    final Echoer.AsyncClient.echo_call[] result = { null };
    final Exception[] error = { null };

    Echoer.AsyncIface echoer = clientProxy.get();
    echoer.echo("Hello", new AsyncMethodCallback<Echoer.AsyncClient.echo_call>() {
        @Override
        public void onComplete(Echoer.AsyncClient.echo_call response) {
            result[0] = response;
            latch.countDown();
        }

        @Override
        public void onError(Exception exception) {
            error[0] = exception;
            latch.countDown();
        }
    });

    latch.await(AWAIT_TIMEOUT, TimeUnit.SECONDS);

    assertThat(error[0], is(nullValue()));
    assertThat(result[0].getResult(), is("Echoed: Hello"));
}

From source file:com.vmware.photon.controller.common.thrift.EndToEndTest.java

License:Open Source License

@Test
public void testEndToEndRpcTimeout() throws Exception {
    TServerSocket transport = new TServerSocket(0);
    Echoer.Processor<SleepyEchoServer> processor = new Echoer.Processor<>(new SleepyEchoServer());
    server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).transportFactory(transportFactory)
            .protocolFactory(protocolFactory).processor(processor));

    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(new Runnable() {
        @Override//  w ww .  j a  va 2 s .  c  om
        public void run() {
            server.serve();
        }
    });

    InetSocketAddress localPort = new InetSocketAddress(transport.getServerSocket().getLocalPort());
    ClientPool<Echoer.AsyncClient> pool = poolFactory.create(new StaticServerSet(localPort),
            new ClientPoolOptions().setMaxClients(10).setMaxWaiters(10));
    ClientProxy<Echoer.AsyncClient> clientProxy = proxyFactory.create(pool);

    final CountDownLatch latch = new CountDownLatch(1);
    final Echoer.AsyncClient.echo_call[] result = { null };
    final Exception[] error = { null };

    Echoer.AsyncClient echoer = clientProxy.get();
    echoer.setTimeout(5);
    echoer.echo("Hello", new AsyncMethodCallback<Echoer.AsyncClient.echo_call>() {
        @Override
        public void onComplete(Echoer.AsyncClient.echo_call response) {
            result[0] = response;
            latch.countDown();
        }

        @Override
        public void onError(Exception exception) {
            error[0] = exception;
            latch.countDown();
        }
    });

    latch.await(AWAIT_TIMEOUT, TimeUnit.SECONDS);

    assertThat(error[0], is(instanceOf(TimeoutException.class)));
    assertTrue(error[0].getMessage().contains("timed out"), "Expecting 'timed out' in error message");
    assertThat(result[0], is(nullValue()));
}

From source file:com.vmware.photon.controller.deployer.DeployerServer.java

License:Open Source License

public void serve() throws UnknownHostException, TTransportException {
    InetAddress registrationIpAddress = InetAddress.getByName(registrationAddress);
    if (registrationIpAddress.isAnyLocalAddress()) {
        logger.error("Using a wildcard registration address will not work with service registry: {}",
                registrationAddress);/*from ww  w. j  a  v  a2  s . c om*/
        throw new IllegalArgumentException("Wildcard registration address");
    }

    InetAddress bindIpAddress = InetAddress.getByName(bind);
    InetSocketAddress bindSocketAddress = new InetSocketAddress(bindIpAddress, port);
    TServerSocket transport = new TServerSocket(bindSocketAddress);

    Deployer.Processor<DeployerService> deployerProcessor = new Deployer.Processor<>(deployerService);
    TMultiplexedProcessor processor = new TMultiplexedProcessor();
    processor.registerProcessor(SERVICE_NAME, deployerProcessor);

    server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).processor(processor)
            .protocolFactory(protocolFactory).transportFactory(transportFactory));

    // Need to re-fetch local port in case it was 0
    InetSocketAddress registrationSocketAddress = new InetSocketAddress(registrationIpAddress,
            transport.getServerSocket().getLocalPort());
    serviceNode = serviceNodeFactory.createSimple("deployer", registrationSocketAddress);

    server.setServerEventHandler(getThriftEventHandler());

    logger.info("Starting deployer ({})", buildInfo);
    logger.info("Listening on: {}", bindSocketAddress);
    logger.info("Registering address: {}", registrationSocketAddress);
    logger.info("HttpClient is: {}", httpClient);
    server.serve();
}

From source file:com.vmware.photon.controller.housekeeper.HousekeeperServer.java

License:Open Source License

public void serve() throws UnknownHostException, TTransportException {
    InetAddress registrationIpAddress = InetAddress.getByName(registrationAddress);
    if (registrationIpAddress.isAnyLocalAddress()) {
        logger.error("Using a wildcard registration address will not work with service registry: {}",
                registrationAddress);// ww w  .  ja v a 2 s  .co  m
        throw new IllegalArgumentException("Wildcard registration address");
    }

    InetAddress bindIpAddress = InetAddress.getByName(bind);
    InetSocketAddress bindSocketAddress = new InetSocketAddress(bindIpAddress, port);
    TServerSocket transport = new TServerSocket(bindSocketAddress);

    Housekeeper.Processor<HousekeeperService> housekeeperProcessor = new Housekeeper.Processor<>(
            housekeeperService);
    TMultiplexedProcessor processor = new TMultiplexedProcessor();
    processor.registerProcessor(SERVICE_NAME, housekeeperProcessor);

    server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).processor(processor)
            .protocolFactory(protocolFactory).transportFactory(transportFactory));

    // Need to re-fetch local port in case it was 0
    InetSocketAddress registrationSocketAddress = new InetSocketAddress(registrationIpAddress,
            transport.getServerSocket().getLocalPort());
    serviceNode = serviceNodeFactory.createSimple("housekeeper", registrationSocketAddress);

    server.setServerEventHandler(getThriftEventHandler());

    logger.info("Starting housekeeper ({})", buildInfo);
    logger.info("Listening on: {}", bindSocketAddress);
    logger.info("Registering address: {}", registrationSocketAddress);
    server.serve();
}

From source file:com.vmware.photon.controller.rootscheduler.RootSchedulerServer.java

License:Open Source License

public void serve() throws TTransportException, UnknownHostException {
    InetAddress registrationIpAddress = InetAddress.getByName(registrationAddress);
    if (registrationIpAddress.isAnyLocalAddress()) {
        logger.error("Using a wildcard registration address will not work with service registry: {}",
                registrationAddress);//from   w  ww. j  ava  2  s.c  o m
        throw new IllegalArgumentException("Wildcard registration address");
    }

    InetAddress bindIpAddress = InetAddress.getByName(bind);
    InetSocketAddress bindSocketAddress = new InetSocketAddress(bindIpAddress, port);
    TServerSocket transport = new TServerSocket(bindSocketAddress);

    RootScheduler.Processor<RootScheduler.Iface> rootSchedulerProcessor = new RootScheduler.Processor<>(
            rootSchedulerService);
    TMultiplexedProcessor processor = new TMultiplexedProcessor();
    processor.registerProcessor("RootScheduler", rootSchedulerProcessor);

    server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).processor(processor)
            .protocolFactory(protocolFactory).transportFactory(transportFactory));

    // Need to re-fetch local port in case it was 0
    InetSocketAddress registrationSocketAddress = new InetSocketAddress(registrationIpAddress,
            transport.getServerSocket().getLocalPort());
    serviceNode = serviceNodeFactory.createSimple("root-scheduler", registrationSocketAddress);
    if (rootSchedulerService instanceof ServiceNodeEventHandler) {
        server.setServerEventHandler(
                thriftFactory.create((ServiceNodeEventHandler) rootSchedulerService, serviceNode));
    }
    logger.info("Starting root scheduler ({})", buildInfo);
    logger.info("Listening on: {}", bindSocketAddress);
    logger.info("Registering address: {}", registrationSocketAddress);
    server.serve();
}