Example usage for org.apache.thrift TServiceClient getOutputProtocol

List of usage examples for org.apache.thrift TServiceClient getOutputProtocol

Introduction

In this page you can find the example usage for org.apache.thrift TServiceClient getOutputProtocol.

Prototype

public TProtocol getOutputProtocol() 

Source Link

Document

Get the TProtocol being used as the output (write) protocol.

Usage

From source file:com.baidu.oped.apm.plugin.thrift.interceptor.client.TServiceClientSendBaseInterceptor.java

License:Apache License

@Override
public void before(Object target, Object[] args) {
    if (isDebug) {
        logger.beforeInterceptor(target, args);
    }/*from ww  w. j  ava 2s.  c  o  m*/
    if (target instanceof TServiceClient) {
        TServiceClient client = (TServiceClient) target;
        TProtocol oprot = client.getOutputProtocol();
        TTransport transport = oprot.getTransport();
        final Trace trace = traceContext.currentRawTraceObject();
        if (trace == null) {
            return;
        }
        ThriftRequestProperty parentTraceInfo = new ThriftRequestProperty();
        final boolean shouldSample = trace.canSampled();
        if (!shouldSample) {
            if (isDebug) {
                logger.debug("set Sampling flag=false");
            }
            parentTraceInfo.setShouldSample(shouldSample);
        } else {
            SpanEventRecorder recorder = trace.traceBlockBegin();
            recorder.recordServiceType(ThriftConstants.THRIFT_CLIENT);

            // retrieve connection information
            String remoteAddress = ThriftConstants.UNKNOWN_ADDRESS;
            if (transport instanceof SocketFieldAccessor) {
                Socket socket = ((SocketFieldAccessor) transport)._$APM$_getSocket();
                if (socket != null) {
                    remoteAddress = ThriftUtils.getHostPort(socket.getRemoteSocketAddress());
                }
            } else {
                if (isDebug) {
                    logger.debug("Invalid target object. Need field accessor({}).",
                            SocketFieldAccessor.class.getName());
                }
            }
            recorder.recordDestinationId(remoteAddress);

            String methodName = ThriftConstants.UNKNOWN_METHOD_NAME;
            if (args[0] instanceof String) {
                methodName = (String) args[0];
            }
            String serviceName = ThriftUtils.getClientServiceName(client);

            String thriftUrl = getServiceUrl(remoteAddress, serviceName, methodName);
            recorder.recordAttribute(ThriftConstants.THRIFT_URL, thriftUrl);

            TraceId nextId = trace.getTraceId().getNextTraceId();
            recorder.recordNextSpanId(nextId.getSpanId());

            parentTraceInfo.setTraceId(nextId.getTransactionId());
            parentTraceInfo.setSpanId(nextId.getSpanId());
            parentTraceInfo.setParentSpanId(nextId.getParentSpanId());

            parentTraceInfo.setFlags(nextId.getFlags());
            parentTraceInfo.setParentApplicationName(traceContext.getApplicationName());
            parentTraceInfo.setParentApplicationType(traceContext.getServerTypeCode());
            parentTraceInfo.setAcceptorHost(remoteAddress);
        }
        InterceptorGroupInvocation currentTransaction = this.group.getCurrentInvocation();
        currentTransaction.setAttachment(parentTraceInfo);
    }
}

From source file:com.navercorp.pinpoint.plugin.thrift.interceptor.client.TServiceClientSendBaseInterceptor.java

License:Apache License

@Override
public void before(Object target, Object[] args) {
    if (isDebug) {
        logger.beforeInterceptor(target, args);
    }//from  w ww  .  ja  va  2 s  .com
    if (target instanceof TServiceClient) {
        TServiceClient client = (TServiceClient) target;
        TProtocol oprot = client.getOutputProtocol();
        TTransport transport = oprot.getTransport();
        final Trace trace = traceContext.currentRawTraceObject();
        if (trace == null) {
            return;
        }
        ThriftRequestProperty parentTraceInfo = new ThriftRequestProperty();
        final boolean shouldSample = trace.canSampled();
        if (!shouldSample) {
            if (isDebug) {
                logger.debug("set Sampling flag=false");
            }
            parentTraceInfo.setShouldSample(shouldSample);
        } else {
            SpanEventRecorder recorder = trace.traceBlockBegin();
            recorder.recordServiceType(THRIFT_CLIENT);

            // retrieve connection information
            String remoteAddress = UNKNOWN_ADDRESS;
            if (transport instanceof SocketFieldAccessor) {
                Socket socket = ((SocketFieldAccessor) transport)._$PINPOINT$_getSocket();
                if (socket != null) {
                    remoteAddress = ThriftUtils.getHostPort(socket.getRemoteSocketAddress());
                }
            } else {
                if (isDebug) {
                    logger.debug("Invalid target object. Need field accessor({}).",
                            SocketFieldAccessor.class.getName());
                }
            }
            recorder.recordDestinationId(remoteAddress);

            String methodName = UNKNOWN_METHOD_NAME;
            if (args[0] instanceof String) {
                methodName = (String) args[0];
            }
            String serviceName = ThriftUtils.getClientServiceName(client);

            String thriftUrl = getServiceUrl(remoteAddress, serviceName, methodName);
            recorder.recordAttribute(THRIFT_URL, thriftUrl);

            TraceId nextId = trace.getTraceId().getNextTraceId();
            recorder.recordNextSpanId(nextId.getSpanId());

            parentTraceInfo.setTraceId(nextId.getTransactionId());
            parentTraceInfo.setSpanId(nextId.getSpanId());
            parentTraceInfo.setParentSpanId(nextId.getParentSpanId());

            parentTraceInfo.setFlags(nextId.getFlags());
            parentTraceInfo.setParentApplicationName(traceContext.getApplicationName());
            parentTraceInfo.setParentApplicationType(traceContext.getServerTypeCode());
            parentTraceInfo.setAcceptorHost(remoteAddress);
        }
        InterceptorGroupInvocation currentTransaction = this.group.getCurrentInvocation();
        currentTransaction.setAttachment(parentTraceInfo);
    }
}

From source file:ezbake.thrift.ThriftUtils.java

License:Apache License

public static void quietlyClose(TServiceClient client) {
    try {/*from  w w w . java2 s  .  c  o  m*/
        client.getOutputProtocol().getTransport().close();
    } catch (Exception ignore) {
        //do nothing
    }
    try {
        client.getInputProtocol().getTransport().close();
    } catch (Exception ignore) {
        //do nothing
    }
}

From source file:org.apache.accumulo.server.tabletserver.ScanRunState.java

License:Apache License

public void run() {
    SecurityUtil.serverLogin();//from  ww w. ja  v  a 2  s .c o m

    try {
        clientAddress = startTabletClientService();
    } catch (UnknownHostException e1) {
        throw new RuntimeException("Failed to start the tablet client service", e1);
    }
    announceExistence();

    ThreadPoolExecutor distWorkQThreadPool = new SimpleThreadPool(
            getSystemConfiguration().getCount(Property.TSERV_WORKQ_THREADS), "distributed work queue");

    bulkFailedCopyQ = new DistributedWorkQueue(ZooUtil.getRoot(instance) + Constants.ZBULK_FAILED_COPYQ);
    try {
        bulkFailedCopyQ.startProcessing(new BulkFailedCopyProcessor(), distWorkQThreadPool);
    } catch (Exception e1) {
        throw new RuntimeException("Failed to start distributed work queue for copying ", e1);
    }

    try {
        logSorter.startWatchingForRecoveryLogs(distWorkQThreadPool);
    } catch (Exception ex) {
        log.error("Error setting watches for recoveries");
        throw new RuntimeException(ex);
    }

    try {
        OBJECT_NAME = new ObjectName(
                "accumulo.server.metrics:service=TServerInfo,name=TabletServerMBean,instance="
                        + Thread.currentThread().getName());
        // Do this because interface not in same package.
        StandardMBean mbean = new StandardMBean(this, TabletServerMBean.class, false);
        this.register(mbean);
        mincMetrics.register();
    } catch (Exception e) {
        log.error("Error registering with JMX", e);
    }

    String masterHost;
    while (!serverStopRequested) {
        // send all of the pending messages
        try {
            MasterMessage mm = null;
            MasterClientService.Client iface = null;

            try {
                // wait until a message is ready to send, or a sever stop
                // was requested
                while (mm == null && !serverStopRequested) {
                    mm = masterMessages.poll(1000, TimeUnit.MILLISECONDS);
                }

                // have a message to send to the master, so grab a
                // connection
                masterHost = getMasterAddress();
                iface = masterConnection(masterHost);
                TServiceClient client = iface;

                // if while loop does not execute at all and mm != null,
                // then
                // finally block should place mm back on queue
                while (!serverStopRequested && mm != null && client != null
                        && client.getOutputProtocol() != null
                        && client.getOutputProtocol().getTransport() != null
                        && client.getOutputProtocol().getTransport().isOpen()) {
                    try {
                        mm.send(SystemCredentials.get().toThrift(instance), getClientAddressString(), iface);
                        mm = null;
                    } catch (TException ex) {
                        log.warn("Error sending message: queuing message again");
                        masterMessages.putFirst(mm);
                        mm = null;
                        throw ex;
                    }

                    // if any messages are immediately available grab em and
                    // send them
                    mm = masterMessages.poll();
                }

            } finally {

                if (mm != null) {
                    masterMessages.putFirst(mm);
                }
                returnMasterConnection(iface);

                UtilWaitThread.sleep(1000);
            }
        } catch (InterruptedException e) {
            log.info("Interrupt Exception received, shutting down");
            serverStopRequested = true;

        } catch (Exception e) {
            // may have lost connection with master
            // loop back to the beginning and wait for a new one
            // this way we survive master failures
            log.error(getClientAddressString() + ": TServerInfo: Exception. Master down?", e);
        }
    }

    // wait for shutdown
    // if the main thread exits oldServer the master listener, the JVM will
    // kill the
    // other threads and finalize objects. We want the shutdown that is
    // running
    // in the master listener thread to complete oldServer this happens.
    // consider making other threads daemon threads so that objects don't
    // get prematurely finalized
    synchronized (this) {
        while (shutdownComplete == false) {
            try {
                this.wait(1000);
            } catch (InterruptedException e) {
                log.error(e.toString());
            }
        }
    }
    log.debug("Stopping Thrift Servers");
    TServerUtils.stopTServer(server);

    try {
        log.debug("Closing filesystem");
        fs.close();
    } catch (IOException e) {
        log.warn("Failed to close filesystem : " + e.getMessage(), e);
    }

    logGCInfo(getSystemConfiguration());

    log.info("TServerInfo: stop requested. exiting ... ");

    try {
        tabletServerLock.unlock();
    } catch (Exception e) {
        log.warn("Failed to release tablet server lock", e);
    }
}

From source file:org.apache.accumulo.tserver.TabletServer.java

License:Apache License

@Override
public void run() {
    SecurityUtil.serverLogin(SiteConfiguration.getInstance());

    // To make things easier on users/devs, and to avoid creating an upgrade path to 1.7
    // We can just make the zookeeper paths before we try to use.
    try {//  w  ww. j  av a  2s.c om
        ZooKeeperInitialization.ensureZooKeeperInitialized(ZooReaderWriter.getInstance(),
                ZooUtil.getRoot(getInstance()));
    } catch (KeeperException | InterruptedException e) {
        log.error("Could not ensure that ZooKeeper is properly initialized", e);
        throw new RuntimeException(e);
    }

    Metrics tserverMetrics = metricsFactory.createTabletServerMetrics(this);

    // Register MBeans
    try {
        tserverMetrics.register();
        mincMetrics.register();
        scanMetrics.register();
        updateMetrics.register();
    } catch (Exception e) {
        log.error("Error registering with JMX", e);
    }

    if (null != authKeyWatcher) {
        log.info("Seeding ZooKeeper watcher for authentication keys");
        try {
            authKeyWatcher.updateAuthKeys();
        } catch (KeeperException | InterruptedException e) {
            // TODO Does there need to be a better check? What are the error conditions that we'd fall out here? AUTH_FAILURE?
            // If we get the error, do we just put it on a timer and retry the exists(String, Watcher) call?
            log.error(
                    "Failed to perform initial check for authentication tokens in ZooKeeper. Delegation token authentication will be unavailable.",
                    e);
        }
    }

    try {
        clientAddress = startTabletClientService();
    } catch (UnknownHostException e1) {
        throw new RuntimeException("Failed to start the tablet client service", e1);
    }
    announceExistence();

    ThreadPoolExecutor distWorkQThreadPool = new SimpleThreadPool(
            getConfiguration().getCount(Property.TSERV_WORKQ_THREADS), "distributed work queue");

    bulkFailedCopyQ = new DistributedWorkQueue(ZooUtil.getRoot(getInstance()) + Constants.ZBULK_FAILED_COPYQ,
            getConfiguration());
    try {
        bulkFailedCopyQ.startProcessing(new BulkFailedCopyProcessor(), distWorkQThreadPool);
    } catch (Exception e1) {
        throw new RuntimeException("Failed to start distributed work queue for copying ", e1);
    }

    try {
        logSorter.startWatchingForRecoveryLogs(distWorkQThreadPool);
    } catch (Exception ex) {
        log.error("Error setting watches for recoveries");
        throw new RuntimeException(ex);
    }

    // Start the thrift service listening for incoming replication requests
    try {
        replicationAddress = startReplicationService();
    } catch (UnknownHostException e) {
        throw new RuntimeException("Failed to start replication service", e);
    }

    // Start the pool to handle outgoing replications
    final ThreadPoolExecutor replicationThreadPool = new SimpleThreadPool(
            getConfiguration().getCount(Property.REPLICATION_WORKER_THREADS), "replication task");
    replWorker.setExecutor(replicationThreadPool);
    replWorker.run();

    // Check the configuration value for the size of the pool and, if changed, resize the pool, every 5 seconds);
    final AccumuloConfiguration aconf = getConfiguration();
    Runnable replicationWorkThreadPoolResizer = new Runnable() {
        @Override
        public void run() {
            int maxPoolSize = aconf.getCount(Property.REPLICATION_WORKER_THREADS);
            if (replicationThreadPool.getMaximumPoolSize() != maxPoolSize) {
                log.info("Resizing thread pool for sending replication work from "
                        + replicationThreadPool.getMaximumPoolSize() + " to " + maxPoolSize);
                replicationThreadPool.setMaximumPoolSize(maxPoolSize);
            }
        }
    };
    SimpleTimer.getInstance(aconf).schedule(replicationWorkThreadPoolResizer, 10000, 30000);

    HostAndPort masterHost;
    while (!serverStopRequested) {
        // send all of the pending messages
        try {
            MasterMessage mm = null;
            MasterClientService.Client iface = null;

            try {
                // wait until a message is ready to send, or a sever stop
                // was requested
                while (mm == null && !serverStopRequested) {
                    mm = masterMessages.poll(1000, TimeUnit.MILLISECONDS);
                }

                // have a message to send to the master, so grab a
                // connection
                masterHost = getMasterAddress();
                iface = masterConnection(masterHost);
                TServiceClient client = iface;

                // if while loop does not execute at all and mm != null,
                // then finally block should place mm back on queue
                while (!serverStopRequested && mm != null && client != null
                        && client.getOutputProtocol() != null
                        && client.getOutputProtocol().getTransport() != null
                        && client.getOutputProtocol().getTransport().isOpen()) {
                    try {
                        mm.send(rpcCreds(), getClientAddressString(), iface);
                        mm = null;
                    } catch (TException ex) {
                        log.warn("Error sending message: queuing message again");
                        masterMessages.putFirst(mm);
                        mm = null;
                        throw ex;
                    }

                    // if any messages are immediately available grab em and
                    // send them
                    mm = masterMessages.poll();
                }

            } finally {

                if (mm != null) {
                    masterMessages.putFirst(mm);
                }
                returnMasterConnection(iface);

                UtilWaitThread.sleep(1000);
            }
        } catch (InterruptedException e) {
            log.info("Interrupt Exception received, shutting down");
            serverStopRequested = true;

        } catch (Exception e) {
            // may have lost connection with master
            // loop back to the beginning and wait for a new one
            // this way we survive master failures
            log.error(getClientAddressString() + ": TServerInfo: Exception. Master down?", e);
        }
    }

    // wait for shutdown
    // if the main thread exits oldServer the master listener, the JVM will
    // kill the other threads and finalize objects. We want the shutdown that is
    // running in the master listener thread to complete oldServer this happens.
    // consider making other threads daemon threads so that objects don't
    // get prematurely finalized
    synchronized (this) {
        while (shutdownComplete == false) {
            try {
                this.wait(1000);
            } catch (InterruptedException e) {
                log.error(e.toString());
            }
        }
    }
    log.debug("Stopping Replication Server");
    TServerUtils.stopTServer(this.replServer);
    log.debug("Stopping Thrift Servers");
    TServerUtils.stopTServer(server);

    try {
        log.debug("Closing filesystem");
        fs.close();
    } catch (IOException e) {
        log.warn("Failed to close filesystem : {}", e.getMessage(), e);
    }

    gcLogger.logGCInfo(getConfiguration());

    log.info("TServerInfo: stop requested. exiting ... ");

    try {
        tabletServerLock.unlock();
    } catch (Exception e) {
        log.warn("Failed to release tablet server lock", e);
    }
}

From source file:tech.sirwellington.alchemy.thrift.clients.Clients.java

License:Apache License

/**
 * Closes a Thrift Client, both the Input and Output Transports.
 *
 * @param client The client to close. Will be ignored if null.
 *
 * @throws TException If the Client cannot be closed
 *//*w w  w.j  a va2s. c  o  m*/
public static void close(TServiceClient client) throws TException {
    if (client != null) {
        try {
            if (client.getInputProtocol() != null && client.getInputProtocol().getTransport() != null) {
                client.getInputProtocol().getTransport().close();
            }
            if (client.getOutputProtocol() != null && client.getOutputProtocol().getTransport() != null) {
                client.getOutputProtocol().getTransport().close();
            }
        } catch (Exception ex) {
            throw new TException(ex);
        }
    }
}