/** * 根据rc的设置来确定创建什么类型的transport; * * @param instance * @return */ protected TTransport createNativeTransport( ServiceInstance<RpcPayload> instance) { TSocket socket = new TSocket(instance.getAddress(), instance.getPort()); socket.setTimeout(socketTimeout); RpcPayload server = instance.getPayload(); if ((server == null) || (server.getTransport() == null) || (server.getTransport().equals("socket"))) { return socket; } else if ("framed-transport".equals(server.getTransport())) { return new TFramedTransport(socket); } // for default, use TSocket; return socket; }
private static int logThrift(HostAndPort address, List<LogEntry> messages) { try { TSocket socket = new TSocket(address.getHost(), address.getPort()); socket.open(); try { TBinaryProtocol tp = new TBinaryProtocol(new TFramedTransport(socket)); assertEquals(new scribe.Client(tp).Log(messages), ResultCode.OK); } finally { socket.close(); } } catch (TException e) { throw new RuntimeException(e); } return 1; }
private static TSocket createClientSocket(boolean secure, HostAndPort address) throws TTransportException { if (!secure) { return new TSocket(address.getHost(), address.getPort()); } try { SSLContext serverSslContext = ClientTestUtils.getClientSslContext(); SSLSocket clientSocket = (SSLSocket) serverSslContext.getSocketFactory().createSocket(address.getHost(), address.getPort()); // clientSocket.setSoTimeout(timeout); return new TSocket(clientSocket); } catch (Exception e) { throw new TTransportException("Error initializing secure socket", e); } }
private static TSocket createSSLSocket(SSLSocketFactory factory, String host, int port, int timeout, List<String> excludeProtocols) throws FlumeException { try { SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(timeout); List<String> enabledProtocols = new ArrayList<String>(); for (String protocol : socket.getEnabledProtocols()) { if (!excludeProtocols.contains(protocol)) { enabledProtocols.add(protocol); } } socket.setEnabledProtocols(enabledProtocols.toArray(new String[0])); return new TSocket(socket); } catch (Exception e) { throw new FlumeException("Could not connect to " + host + " on port " + port, e); } }
@Test public void testScribeMessage() throws Exception { TTransport transport = new TFramedTransport(new TSocket("localhost", port)); TProtocol protocol = new TBinaryProtocol(transport); Scribe.Client client = new Scribe.Client(protocol); transport.open(); LogEntry logEntry = new LogEntry("INFO", "Sending info msg to scribe source"); List<LogEntry> logEntries = new ArrayList<LogEntry>(1); logEntries.add(logEntry); client.Log(logEntries); // try to get it from Channels Transaction tx = memoryChannel.getTransaction(); tx.begin(); Event e = memoryChannel.take(); Assert.assertNotNull(e); Assert.assertEquals("Sending info msg to scribe source", new String(e.getBody())); tx.commit(); tx.close(); }
@Override public Pair<TTransport, Bmv2DeviceThriftClient> load(DeviceId deviceId) throws TTransportException { log.debug("Instantiating new client... > deviceId={}", deviceId); // Make the expensive call Bmv2Device device = Bmv2Device.of(deviceId); TTransport transport = new TSocket(device.thriftServerHost(), device.thriftServerPort()); TProtocol protocol = new TBinaryProtocol(transport); // Our BMv2 device implements multiple Thrift services, create a client for each one on the same transport. Standard.Client standardClient = new Standard.Client( new TMultiplexedProtocol(protocol, "standard")); SimpleSwitch.Client simpleSwitch = new SimpleSwitch.Client( new TMultiplexedProtocol(protocol, "simple_switch")); // Wrap clients so to automatically have synchronization and resiliency to connectivity errors Standard.Iface safeStandardClient = SafeThriftClient.wrap(standardClient, Standard.Iface.class, options); SimpleSwitch.Iface safeSimpleSwitchClient = SafeThriftClient.wrap(simpleSwitch, SimpleSwitch.Iface.class, options); Bmv2DeviceThriftClient client = new Bmv2DeviceThriftClient(deviceId, transport, safeStandardClient, safeSimpleSwitchClient); return Pair.of(transport, client); }
public static void startClient(String ip ,int port ,int timeout) throws Exception { TTransport transport = new TSocket(ip,port,timeout); TProtocol protocol = new TBinaryProtocol(transport); leafrpc.Client client = new leafrpc.Client(protocol); transport.open(); int i = 0; while(i < 2000000) { client.getID(""); ++i; } transport.close(); }
public static void startClient2(String ip ,int port ,int timeout) throws Exception { TTransport transport = new TFramedTransport(new TSocket(ip,port,timeout)); TProtocol protocol = new TBinaryProtocol(transport); leafrpc.Client client = new leafrpc.Client(protocol); transport.open(); for(int i = 0; i< 1000000; i++) { client.getID(""); if (i % 100000 == 0) { System.out.println(Thread.currentThread().getName() + " " + client.getID("")); } //ai.incrementAndGet(); } transport.close(); }
@Override public TServiceClient makeObject() throws Exception { InetSocketAddress address = serverAddressProvider.selector(); if(address==null){ new ThriftException("No provider available for remote service"); } TSocket tsocket = new TSocket(address.getHostName(), address.getPort()); TTransport transport = new TFramedTransport(tsocket); TProtocol protocol = new TBinaryProtocol(transport); TServiceClient client = this.clientFactory.getClient(protocol); transport.open(); if (callback != null) { try { callback.make(client); } catch (Exception e) { logger.warn("makeObject:{}", e); } } return client; }
@Override public TServiceClient makeObject() throws Exception { TSocket tsocket = new TSocket(server.getHost(), server.getPort()); tsocket.open(); // TTransport transport = new TFramedTransport(tsocket); TJSONProtocol protocol = new TJSONProtocol(tsocket); TMultiplexedProtocol uProtocol=new TMultiplexedProtocol(protocol, proccessName); TServiceClient client = this.clientFactory.getClient(uProtocol); if (callback != null) { try { callback.make(client); } catch (Exception e) { logger.warn("makeObject:{}", e); } } return client; }
/** * {@inheritDoc} */ @Override public ServerContext createContext(final TProtocol input, final TProtocol output) { final String userName = "metacat-thrift-interface"; String clientHost = null; //requestContext.getHeaderString("X-Forwarded-For"); final long requestThreadId = Thread.currentThread().getId(); final TTransport transport = input.getTransport(); if (transport instanceof TSocket) { final TSocket thriftSocket = (TSocket) transport; clientHost = thriftSocket.getSocket().getInetAddress().getHostAddress(); } final CatalogServerRequestContext context = new CatalogServerRequestContext( userName, null, clientHost, null, "hive", requestThreadId ); MetacatContextManager.setContext(context); return context; }
@Test public void thriftTest() throws TException { TSocket transport = new TSocket("127.0.0.1", 8080); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); TMultiplexedProtocol mp1 = new TMultiplexedProtocol(protocol,"helloWorld"); HelloWorld.Client client = new HelloWorld.Client(mp1); User user = new User(); user.setName("{\"proid\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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true); Result result = client.createNewBaseResInfo(user); Assert.notNull(result); System.out.println(result.getMsg()); System.out.println("end>>>>>>>>>>>>>>>>"); }
public Worker(int id, long durationMillis, String path, int globals) throws IOException { this.id = id; this.workerDuration = durationMillis; this.localPath = path + "/f" + Integer.toString(id); this.globalPath = "/f" + Integer.toString(id); this.instanceMap = new HashMap<>(); this.globals = globals; String replicaHost = replicaAddr.split(":")[0]; int replicaPort = Integer.parseInt(replicaAddr.split(":")[1]); TTransport transport = new TSocket(replicaHost, replicaPort); try { transport.open(); } catch (TTransportException e) { throw new RuntimeException(e); } TProtocol protocol = new TBinaryProtocol(transport); c = new FuseOps.Client(protocol); out = new BufferedWriter(new FileWriter(new File(logPrefix + this.id))); }
public Worker(int id, long durationMillis, String path, int globals) throws IOException { this.id = id; this.workerDuration = durationMillis; this.path = path; this.globals = globals; String replicaHost = replicaAddr.split(":")[0]; int replicaPort = Integer.parseInt(replicaAddr.split(":")[1]); TTransport transport = new TSocket(replicaHost, replicaPort); try { transport.open(); } catch (TTransportException e) { throw new RuntimeException(e); } TProtocol protocol = new TBinaryProtocol(transport); c = new FuseOps.Client(protocol); out = new BufferedWriter(new FileWriter(new File(logPrefix + this.id))); }
public Worker(int id, String path) throws IOException { this.id = id; this.path = path; this.localPath = path + "/f" + Integer.toString(id); this.globalPath = "/f" + Integer.toString(id); this.instanceMap = new HashMap<>(); String replicaHost = replicaAddr.split(":")[0]; int replicaPort = Integer.parseInt(replicaAddr.split(":")[1]); TTransport transport = new TSocket(replicaHost, replicaPort); try { transport.open(); } catch (TTransportException e) { throw new RuntimeException(e); } TProtocol protocol = new TBinaryProtocol(transport); c = new FuseOps.Client(protocol); }
@Override public Client create() throws Exception { TSocket transport = new TSocket(host, port); try { transport.open(); } catch (TTransportException e) { throw new InterpreterException(e); } TProtocol protocol = new TBinaryProtocol(transport); Client client = new RemoteInterpreterService.Client(protocol); synchronized (clientSocketMap) { clientSocketMap.put(client, transport); } return client; }
private static void connectToCMD() { QueryInput query_input = new QueryInput(); query_input.type = "ensemble"; query_input.data = new ArrayList<String>(); query_input.data.add("localhost"); query_input.tags = new ArrayList<String>(); query_input.tags.add("9090"); QuerySpec spec = new QuerySpec(); spec.content = new ArrayList<QueryInput>(); spec.content.add(query_input); // Initialize thrift objects. TTransport transport = new TSocket("localhost", 8080); TProtocol protocol = new TBinaryProtocol(new TFramedTransport(transport)); LucidaService.Client client = new LucidaService.Client(protocol); try { transport.open(); System.out.println("Connecting to CMD at port " + 8080); // Register itself to CMD. client.create("", spec); transport.close(); System.out.println("Successfully connected to CMD"); } catch (TException x) { x.printStackTrace(); } }
@SuppressWarnings("unchecked") @Override public PooledObject makeObject() throws Exception { //logger.debug("makeObject..........."); try { String host = this.host; int port = this.port; int timeout = this.timeout; TFramedTransport transport = new TFramedTransport(new TSocket(host, port, timeout)); TBinaryProtocol protocol = new TBinaryProtocol(transport); FrcService.Client client = new FrcService.Client(protocol, protocol); transport.open(); RpcClient<Client> rpcClient = new RpcClient(client, transport, 1); return this.wrap(rpcClient); } catch (Exception e) { logger.error("exception", e); return null; } }
/** * 创建原始连接的方法 * * @throws ThriftConnectionPoolException * 创建连接出现问题时抛出该异常 */ @SuppressWarnings("unchecked") private void createConnection() throws ThriftConnectionPoolException { try { transport = new TSocket(host, port, connectionTimeOut); transport.open(); TProtocol protocol = createTProtocol(transport); // 反射实例化客户端对象 Constructor<? extends TServiceClient> clientConstructor = clientClass.getConstructor(TProtocol.class); client = (T) clientConstructor.newInstance(protocol); if (logger.isDebugEnabled()) { logger.debug("创建新连接成功:" + host + " 端口:" + port); } } catch (Exception e) { throw new ThriftConnectionPoolException("无法连接服务器:" + host + " 端口:" + port); } }
/** * Used for getting a client to the CoronaProxyJobTracker * @param conf * @return Returns a client to the CPJT * @throws IOException */ public static CoronaProxyJobTrackerService.Client getPJTClient(CoronaConf conf) throws IOException { InetSocketAddress address = NetUtils.createSocketAddr(conf.getProxyJobTrackerThriftAddress()); TFramedTransport transport = new TFramedTransport( new TSocket(address.getHostName(), address.getPort())); CoronaProxyJobTrackerService.Client client = new CoronaProxyJobTrackerService.Client(new TBinaryProtocol(transport)); try { transport.open(); } catch (TException e) { LOG.info("Transport Exception: ", e); } return client; }
/** * Turns on the Safe Mode if safeMode is true. Turns off the Safe Mode if * safeMode is false. * @param safeMode Is true if we want the Safe Mode to be on. false * otherwise. * @return 0 if successful. * @throws IOException */ private int setSafeMode(boolean safeMode) throws IOException { // Get the current configuration CoronaConf conf = new CoronaConf(getConf()); InetSocketAddress address = NetUtils.createSocketAddr(conf .getClusterManagerAddress()); TFramedTransport transport = new TFramedTransport( new TSocket(address.getHostName(), address.getPort())); ClusterManagerService.Client client = new ClusterManagerService.Client( new TBinaryProtocol(transport)); try { transport.open(); if (client.setSafeMode(safeMode)) { System.out.println("The safeMode is: " + (safeMode ? "ON" : "OFF")); } else { System.err.println("Could not set the safeMode flag"); } } catch (TException e) { throw new IOException(e); } return 0; }
/** * Persists the state of the ClusterManager * @return 0 if successful. * @throws IOException */ private int persistState() throws IOException { // Get the current configuration CoronaConf conf = new CoronaConf(getConf()); InetSocketAddress address = NetUtils.createSocketAddr(conf .getClusterManagerAddress()); TFramedTransport transport = new TFramedTransport( new TSocket(address.getHostName(), address.getPort())); ClusterManagerService.Client client = new ClusterManagerService.Client( new TBinaryProtocol(transport)); try { transport.open(); if (!client.persistState()) { System.err.println("Persisting Cluster Manager state failed. "); } } catch (TException e) { throw new IOException(e); } return 0; }
private synchronized void initializeClusterManagerClient() throws IOException { // Connect to cluster manager thrift service String target = CoronaConf.getClusterManagerAddress(fConf); LOG.info("Connecting to Cluster Manager at " + target); InetSocketAddress address = NetUtils.createSocketAddr(target); transport = new TFramedTransport( new TSocket(address.getHostName(), address.getPort())); TProtocol protocol = new TBinaryProtocol(transport); client = new ClusterManagerService.Client(protocol); try { transport.open(); } catch (TTransportException e) { throw new IOException(e); } }
private void setup(String server, int port) throws Exception { /* Establish a thrift connection to the cassandra instance */ TSocket socket = new TSocket(server, port); System.out.println(" connected to " + server + ":" + port + "."); TBinaryProtocol binaryProtocol = new TBinaryProtocol(new TFramedTransport(socket)); Cassandra.Client cassandraClient = new Cassandra.Client(binaryProtocol); socket.open(); thriftClient = cassandraClient; String seed = DatabaseDescriptor.getSeeds().iterator().next().getHostAddress(); conf = new Configuration(); ConfigHelper.setOutputPartitioner(conf, DatabaseDescriptor.getPartitioner().getClass().getName()); ConfigHelper.setOutputInitialAddress(conf, seed); ConfigHelper.setOutputRpcPort(conf, Integer.toString(DatabaseDescriptor.getRpcPort())); }
CassandraClient(String hostName, int port, boolean framed) throws TTransportException { TSocket socket = new TSocket(hostName, port); transport = (framed) ? socket : new TFastFramedTransport(socket); transport.open(); client = new Cassandra.Client(new TBinaryProtocol(transport)); try { client.set_cql_version("3.0.0"); } catch (Exception e) { throw new RuntimeException(e); } }
private static Cassandra.Client createThriftClient(String host, int port, String user, String passwd) throws Exception { TSocket socket = new TSocket(host, port); TTransport trans = new TFramedTransport(socket); trans.open(); TProtocol protocol = new TBinaryProtocol(trans); Cassandra.Client client = new Cassandra.Client(protocol); if (user != null && passwd != null) { Map<String, String> credentials = new HashMap<String, String>(); credentials.put(IAuthenticator.USERNAME_KEY, user); credentials.put(IAuthenticator.PASSWORD_KEY, passwd); AuthenticationRequest authenticationRequest = new AuthenticationRequest(credentials); client.login(authenticationRequest); } return client; }
@Test public void testOneway() throws IOException, TException, Failure, InterruptedException { try (TSocket socket = new TSocket("localhost", port)) { socket.open(); TProtocol protocol = new TBinaryProtocol(socket); Client client = new Client(protocol); AtomicBoolean called = new AtomicBoolean(); doAnswer(i -> { called.set(true); return null; }).when(impl).ping(); client.ping(); waitAtMost(Duration.ONE_HUNDRED_MILLISECONDS).untilTrue(called); verify(impl).ping(); verify(instrumentation).onComplete(anyDouble(), any(PServiceCall.class), isNull()); verifyNoMoreInteractions(impl, instrumentation); } }
public boolean process(final TProtocol inProt, final TProtocol outProt) throws TException { // populating request context ReqContext req_context = ReqContext.context(); TTransport trans = inProt.getTransport(); // Sasl transport TSaslServerTransport saslTrans = (TSaslServerTransport) trans; // remote address TSocket tsocket = (TSocket) saslTrans.getUnderlyingTransport(); Socket socket = tsocket.getSocket(); req_context.setRemoteAddress(socket.getInetAddress()); // remote subject SaslServer saslServer = saslTrans.getSaslServer(); String authId = saslServer.getAuthorizationID(); Subject remoteUser = new Subject(); remoteUser.getPrincipals().add(new User(authId)); req_context.setSubject(remoteUser); // invoke service handler return wrapped.process(inProt, outProt); }
/** * @return */ public boolean initialize() { for (final ClientMetadata metadata : clientsMeta) { try { log.info("Opening server socket on port = {}, host name = {}", metadata.getPortNum(), metadata.getHostName()); TTransport socket = new TFramedTransport(new TSocket(metadata.getHostName(), metadata.getPortNum())); final TBinaryProtocol protocol = new TBinaryProtocol(socket); final CoresetService.Client client = new CoresetService.Client(protocol); socket.open(); log.info("Initializing coreset service with parameters, " + "k = {}, sample size = {} and algorithm = {}", kValue, sampleSize, coresetAlgName); if (!client.initialize(kValue, sampleSize, coresetAlgName)) { log.error("Server wasn't able to accept initialization parameters, please read server logs."); return false; } metadata.setSocket(socket); clients.put(metadata, client); } catch (Exception e) { e.printStackTrace(); return false; } } return true; }
@Test public void connectToKeyspace() throws Exception { TTransport tr = new TFramedTransport(new TSocket("localhost", Integer.getInteger( "rpcPort", 9160 ))); TProtocol proto = new TBinaryProtocol(tr); Cassandra.Client client = new Cassandra.Client(proto); tr.open(); try { assertThat(client.describe_keyspace("testkeyspace").getStrategy_options().entrySet(), hasItem((Map.Entry<String, String>)new AbstractMap.SimpleEntry<String,String>("replication_factor","1"))); } finally { tr.close(); } }
@Test public void connectToKeyspace() throws Exception { TTransport tr = new TFramedTransport(new TSocket("localhost", Integer.getInteger( "rpcPort", 9160 ))); TProtocol proto = new TBinaryProtocol(tr); Cassandra.Client client = new Cassandra.Client(proto); tr.open(); try { assertThat(client.describe_keyspace("testkeyspacewithspace").getStrategy_options().entrySet(), hasItem((Map.Entry<String, String>)new AbstractMap.SimpleEntry<String,String>("replication_factor","1"))); } finally { tr.close(); } }
private boolean open() { try { TSocket socket = new TSocket((String) config.get(KEY_SCRIBE_HOST), TypeUtils.getInteger(config.get(KEY_SCRIBE_PORT)), TypeUtils.getInteger(config.get(KEY_SCRIBE_TIMEOUT_MS))); transport = new TFramedTransport(socket); transport.open(); } catch (TException tx) { LOG.log(Level.SEVERE, "Failed to open connection to scribe server " + connectionString(), tx); return false; } LOG.info("Opened connection to scribe server " + connectionString()); TProtocol protocol = new TBinaryProtocol(transport); client = new scribe.Client(protocol); return true; }
public static void main(String[] args) throws IOException { try { TTransport transport = new TFramedTransport(new TSocket("localhost", 9090)); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); Calculator.Client client = new Calculator.Client(protocol); perform(client); transport.close(); } catch (TException x) { x.printStackTrace(); } }
public static void main(String[] args) { try { TTransport transport = new TSocket("localhost", 9090); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); Calculator.Client client = new Calculator.Client(protocol); perform(client); transport.close(); } catch (TException x) { x.printStackTrace(); } }