Search in sources :

Example 6 with TServer

use of org.apache.thrift.server.TServer in project mlib by myshzzx.

the class ThriftServerFactory method build.

/**
 * @return build but not start server.
 * @throws Exception
 */
@SuppressWarnings("ConstantConditions")
public TServer build() throws Exception {
    final TServer server;
    int poolSize = Runtime.getRuntime().availableProcessors() * 2;
    poolSize = Math.max(poolSize, this.serverPoolSize);
    AtomicInteger tpi = new AtomicInteger(1);
    ThreadPoolExecutor tPool = new ThreadPoolExecutor(poolSize, poolSize, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), r -> {
        Thread t = new Thread(r, "tServer-" + serverTPI.getAndIncrement() + "-" + tpi.getAndIncrement());
        t.setDaemon(true);
        return t;
    });
    tPool.allowCoreThreadTimeOut(true);
    if (useTLS) {
        // TLS server
        TSSLTransportFactory.TSSLTransportParameters transportParams = new TSSLTransportFactory.TSSLTransportParameters();
        transportParams.setKeyStore(ThriftServerFactory.class.getClassLoader().getResource(this.selfKeyStore).getPath(), this.selfKeyStorePw);
        transportParams.requireClientAuth(this.isRequireClientAuth);
        if (this.isRequireClientAuth)
            transportParams.setTrustStore(ThriftServerFactory.class.getClassLoader().getResource(this.trustKeyStore).getPath(), this.trustKeyStorePw);
        TServerSocket serverTransport = TSSLTransportFactory.getServerSocket(this.serverPort, this.clientTimeout, InetAddress.getByName(this.serverHost), transportParams);
        server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(this.processor).protocolFactory(new TCompactProtocol.Factory()).executorService(tPool));
    } else {
        // Non security Server
        TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(new InetSocketAddress(this.serverHost, this.serverPort), this.clientTimeout);
        server = new THsHaServer(new THsHaServer.Args(serverTransport).processor(this.processor).protocolFactory(new TCompactProtocol.Factory()).transportFactory(new TFramedTransport.Factory(nonTLSServerMaxFrameSize)).executorService(tPool));
    }
    if (this.serverEventHandler != null) {
        server.setServerEventHandler(this.serverEventHandler);
    }
    return server;
}
Also used : TServer(org.apache.thrift.server.TServer) InetSocketAddress(java.net.InetSocketAddress) TSSLTransportFactory(org.apache.thrift.transport.TSSLTransportFactory) TSSLTransportFactory(org.apache.thrift.transport.TSSLTransportFactory) TCompactProtocol(org.apache.thrift.protocol.TCompactProtocol) TServerSocket(org.apache.thrift.transport.TServerSocket) THsHaServer(org.apache.thrift.server.THsHaServer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TNonblockingServerSocket(org.apache.thrift.transport.TNonblockingServerSocket) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) TThreadPoolServer(org.apache.thrift.server.TThreadPoolServer)

Example 7 with TServer

use of org.apache.thrift.server.TServer in project HackTutorial by linrongbin16.

the class Server method main.

public static void main(String[] args) throws Exception {
    ServerSocket socket = new ServerSocket(30003);
    TServerSocket serverTransport = new TServerSocket(socket);
    Basic.BasicService.Processor processor = new Basic.BasicService.Processor(new BasicServiceImpl());
    TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));
    System.out.println("Server Starting...");
    server.serve();
}
Also used : TServerSocket(org.apache.thrift.transport.TServerSocket) Args(org.apache.thrift.server.TServer.Args) TServer(org.apache.thrift.server.TServer) ServerSocket(java.net.ServerSocket) TServerSocket(org.apache.thrift.transport.TServerSocket) TSimpleServer(org.apache.thrift.server.TSimpleServer)

Example 8 with TServer

use of org.apache.thrift.server.TServer in project accumulo by apache.

the class TestThrift1474 method test.

@Test
public void test() throws IOException, TException, InterruptedException {
    TServerSocket serverTransport = new TServerSocket(0);
    serverTransport.listen();
    int port = serverTransport.getServerSocket().getLocalPort();
    TestServer handler = new TestServer();
    ThriftTest.Processor<ThriftTest.Iface> processor = new ThriftTest.Processor<>(handler);
    TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport);
    args.stopTimeoutVal = 10;
    args.stopTimeoutUnit = TimeUnit.MILLISECONDS;
    final TServer server = new TThreadPoolServer(args.processor(processor));
    Thread thread = new Thread() {

        @Override
        public void run() {
            server.serve();
        }
    };
    thread.start();
    while (!server.isServing()) {
        sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
    }
    TTransport transport = new TSocket("localhost", port);
    transport.open();
    TProtocol protocol = new TBinaryProtocol(transport);
    ThriftTest.Client client = new ThriftTest.Client(protocol);
    assertTrue(client.success());
    assertFalse(client.fails());
    try {
        client.throwsError();
        fail("no exception thrown");
    } catch (ThriftSecurityException ex) {
    // expected
    }
    server.stop();
    thread.join();
}
Also used : TServer(org.apache.thrift.server.TServer) ThriftSecurityException(org.apache.accumulo.core.client.impl.thrift.ThriftSecurityException) TServerSocket(org.apache.thrift.transport.TServerSocket) TBinaryProtocol(org.apache.thrift.protocol.TBinaryProtocol) TProtocol(org.apache.thrift.protocol.TProtocol) ThriftTest(org.apache.accumulo.core.client.impl.thrift.ThriftTest) TTransport(org.apache.thrift.transport.TTransport) TThreadPoolServer(org.apache.thrift.server.TThreadPoolServer) TSocket(org.apache.thrift.transport.TSocket) Test(org.junit.Test) ThriftTest(org.apache.accumulo.core.client.impl.thrift.ThriftTest)

Example 9 with TServer

use of org.apache.thrift.server.TServer in project accumulo by apache.

the class TracerTest method testThrift.

@Test
public void testThrift() throws Exception {
    TestReceiver tracer = new TestReceiver();
    org.apache.htrace.Trace.addReceiver(tracer);
    ServerSocket socket = new ServerSocket(0);
    TServerSocket transport = new TServerSocket(socket);
    transport.listen();
    TThreadPoolServer.Args args = new TThreadPoolServer.Args(transport);
    args.processor(new Processor<Iface>(TraceWrap.service(new Service())));
    final TServer tserver = new TThreadPoolServer(args);
    Thread t = new Thread() {

        @Override
        public void run() {
            tserver.serve();
        }
    };
    t.start();
    TTransport clientTransport = new TSocket(new Socket("localhost", socket.getLocalPort()));
    TestService.Iface client = new TestService.Client(new TBinaryProtocol(clientTransport), new TBinaryProtocol(clientTransport));
    client = TraceWrap.client(client);
    assertFalse(client.checkTrace(null, "test"));
    Span start = Trace.on("start");
    assertTrue(client.checkTrace(null, "my test"));
    start.stop();
    assertNotNull(tracer.traces.get(start.traceId()));
    String[] traces = { "my test", "checkTrace", "client:checkTrace", "start" };
    assertTrue(tracer.traces.get(start.traceId()).size() == traces.length);
    for (int i = 0; i < traces.length; i++) assertEquals(traces[i], tracer.traces.get(start.traceId()).get(i).description);
    tserver.stop();
    t.join(100);
}
Also used : TServer(org.apache.thrift.server.TServer) TestService(org.apache.accumulo.tracer.thrift.TestService) TestService(org.apache.accumulo.tracer.thrift.TestService) ServerSocket(java.net.ServerSocket) TServerSocket(org.apache.thrift.transport.TServerSocket) Span(org.apache.accumulo.core.trace.Span) TServerSocket(org.apache.thrift.transport.TServerSocket) Iface(org.apache.accumulo.tracer.thrift.TestService.Iface) Iface(org.apache.accumulo.tracer.thrift.TestService.Iface) TBinaryProtocol(org.apache.thrift.protocol.TBinaryProtocol) TTransport(org.apache.thrift.transport.TTransport) TThreadPoolServer(org.apache.thrift.server.TThreadPoolServer) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) TSocket(org.apache.thrift.transport.TSocket) TServerSocket(org.apache.thrift.transport.TServerSocket) TSocket(org.apache.thrift.transport.TSocket) Test(org.junit.Test)

Example 10 with TServer

use of org.apache.thrift.server.TServer in project accumulo by apache.

the class TServerUtils method startTServer.

/**
 * Start the appropriate Thrift server (SSL or non-blocking server) for the given parameters. Non-null SSL parameters will cause an SSL server to be started.
 *
 * @return A ServerAddress encapsulating the Thrift server created and the host/port which it is bound to.
 */
public static ServerAddress startTServer(ThriftServerType serverType, TimedProcessor processor, TProtocolFactory protocolFactory, String serverName, String threadName, int numThreads, int numSTThreads, long timeBetweenThreadChecks, long maxMessageSize, SslConnectionParams sslParams, SaslServerConnectionParams saslParams, long serverSocketTimeout, HostAndPort... addresses) throws TTransportException {
    // This is presently not supported. It's hypothetically possible, I believe, to work, but it would require changes in how the transports
    // work at the Thrift layer to ensure that both the SSL and SASL handshakes function. SASL's quality of protection addresses privacy issues.
    checkArgument(!(sslParams != null && saslParams != null), "Cannot start a Thrift server using both SSL and SASL");
    ServerAddress serverAddress = null;
    for (HostAndPort address : addresses) {
        try {
            switch(serverType) {
                case SSL:
                    log.debug("Instantiating SSL Thrift server");
                    serverAddress = createSslThreadPoolServer(address, processor, protocolFactory, serverSocketTimeout, sslParams, serverName, numThreads, numSTThreads, timeBetweenThreadChecks);
                    break;
                case SASL:
                    log.debug("Instantiating SASL Thrift server");
                    serverAddress = createSaslThreadPoolServer(address, processor, protocolFactory, serverSocketTimeout, saslParams, serverName, threadName, numThreads, numSTThreads, timeBetweenThreadChecks);
                    break;
                case THREADPOOL:
                    log.debug("Instantiating unsecure TThreadPool Thrift server");
                    serverAddress = createBlockingServer(address, processor, protocolFactory, maxMessageSize, serverName, numThreads, numSTThreads, timeBetweenThreadChecks);
                    break;
                // Intentional passthrough -- Our custom wrapper around HsHa is the default
                case CUSTOM_HS_HA:
                default:
                    log.debug("Instantiating default, unsecure custom half-async Thrift server");
                    serverAddress = createNonBlockingServer(address, processor, protocolFactory, serverName, threadName, numThreads, numSTThreads, timeBetweenThreadChecks, maxMessageSize);
            }
            break;
        } catch (TTransportException e) {
            log.warn("Error attempting to create server at {}. Error: {}", address.toString(), e.getMessage());
        }
    }
    if (null == serverAddress) {
        throw new TTransportException("Unable to create server on addresses: " + Arrays.toString(addresses));
    }
    final TServer finalServer = serverAddress.server;
    Runnable serveTask = new Runnable() {

        @Override
        public void run() {
            try {
                finalServer.serve();
            } catch (Error e) {
                Halt.halt("Unexpected error in TThreadPoolServer " + e + ", halting.", 1);
            }
        }
    };
    serveTask = new LoggingRunnable(TServerUtils.log, serveTask);
    Thread thread = new Daemon(serveTask, threadName);
    thread.start();
    // check for the special "bind to everything address"
    if (serverAddress.address.getHost().equals("0.0.0.0")) {
        // can't get the address from the bind, so we'll do our best to invent our hostname
        try {
            serverAddress = new ServerAddress(finalServer, HostAndPort.fromParts(InetAddress.getLocalHost().getHostName(), serverAddress.address.getPort()));
        } catch (UnknownHostException e) {
            throw new TTransportException(e);
        }
    }
    return serverAddress;
}
Also used : HostAndPort(org.apache.accumulo.core.util.HostAndPort) LoggingRunnable(org.apache.accumulo.fate.util.LoggingRunnable) Daemon(org.apache.accumulo.core.util.Daemon) UnknownHostException(java.net.UnknownHostException) TServer(org.apache.thrift.server.TServer) LoggingRunnable(org.apache.accumulo.fate.util.LoggingRunnable) TTransportException(org.apache.thrift.transport.TTransportException)

Aggregations

TServer (org.apache.thrift.server.TServer)33 TServerSocket (org.apache.thrift.transport.TServerSocket)16 TProcessor (org.apache.thrift.TProcessor)12 TNonblockingServerSocket (org.apache.thrift.transport.TNonblockingServerSocket)11 TBinaryProtocol (org.apache.thrift.protocol.TBinaryProtocol)9 TThreadPoolServer (org.apache.thrift.server.TThreadPoolServer)9 Test (org.junit.Test)9 TProtocolFactory (org.apache.thrift.protocol.TProtocolFactory)8 TCompactProtocol (org.apache.thrift.protocol.TCompactProtocol)7 TThreadedSelectorServer (org.apache.thrift.server.TThreadedSelectorServer)7 TServerTransport (org.apache.thrift.transport.TServerTransport)7 TTransportFactory (org.apache.thrift.transport.TTransportFactory)7 InetSocketAddress (java.net.InetSocketAddress)6 TFramedTransport (org.apache.thrift.transport.TFramedTransport)6 ConfigurationCopy (org.apache.accumulo.core.conf.ConfigurationCopy)5 ServerAddress (org.apache.accumulo.server.rpc.ServerAddress)5 TProtocol (org.apache.thrift.protocol.TProtocol)5 TTransport (org.apache.thrift.transport.TTransport)5 IOException (java.io.IOException)4 ServerSocket (java.net.ServerSocket)4