Beispiel #1
0
	def __init__ (self, port):
		self.transport = TSocket.TSocket('localhost', port)
		self.transport = TTransport.TBufferedTransport(self.transport)
		protocol = TBinaryProtocol.TBinaryProtocol(self.transport)

		self.client = Disambiguation.Client(protocol)
Beispiel #2
0
 def __init__(self, host, port):
     self._socket = TSocket.TSocket(host, port)
     self._transport = TTransport.TBufferedTransport(self._socket)
     self._protocol = TBinaryProtocol.TBinaryProtocolAccelerated(
         self._transport)
     super(CassandraClientHelper, self).__init__(self._protocol)
Beispiel #3
0
from thrift.protocol import TBinaryProtocol
from thrift.transport import TSocket, TTransport
from thrift.server import TServer

__HOST = '127.0.0.1'
__PORT = '8080'


class empServiceHandler(object):
    # 注释

    def getEmpByName(self, name):
        return ttypes.empModel

    def getEmpByeMisNo(self, mis):
        return ttypes.empModel


if __name__ == '__main__':
    handler = empServiceHandler()

    process = empService.Processor(handler)
    trans = TSocket.TServerSocket(__HOST, __PORT)
    tfact = TTransport.TBufferedTransportFactory()
    pfact = TBinaryProtocol.TBinaryProtocolFactory()

    rpcserv = TServer.TSimpleServer(process, trans, tfact, pfact)

    print('Starting rpc server at ', __PORT, ':', __HOST)
    rpcserv.serve()
Beispiel #4
0
def pandas_read_dataframe(config: dict, ranges: tuple, columns: list, meta: dict):
    if config['table'] is None:
        return None

    ret = {}

    # try:
    transport = TSocket.TSocket(config['proxy_host'], config['proxy_port'])
    transport = TTransport.TFramedTransport(transport)
    protocol = TCompactProtocol.TCompactProtocol(transport)
    client = AccumuloProxy.Client(protocol)
    transport.open()

    login = client.login(config['user'], {'password': config['password']})
    auths = client.getUserAuthorizations(login, config['user'])

    # there really has to be something, even if its ('', None), meaning entire table range
    scan_ranges = [] if ranges is not None else None
    if ranges[1] is None:
        r = Range(Key(ranges[0]), True, None, True)
        scan_ranges.append(r)

        log.debug("\t{0}: Row Ranges: {1}-{2}".format(threading.get_ident(), r.start.row, ''))
    else:
        r = Range(Key(ranges[0]), True, Key(ranges[1]), False)
        scan_ranges.append(r)

        log.debug("\t{0}: Row Ranges: {1}-{2}".format(threading.get_ident(), r.start.row, r.stop.row))

    scan_columns = []
    if columns is not None:
        for column in columns:
            c = ScanColumn(column, None)
            scan_columns.append(c)

            log.debug("\t{0}: Scan Column: {1}".format(threading.get_ident(), c))
    else:
        scan_columns = None

    log.debug(f"{scan_columns}, {scan_ranges}")
    options = BatchScanOptions(auths, scan_ranges, scan_columns, [], None)
    cookie = client.createBatchScanner(login, config['table'], options)

    count = 0
    entries = 0
    while client.hasNext(cookie):
        for entry in client.nextK(cookie, 1000).results:
            log.debug("\t{0}: Read row: {1}, {2}, {3}".format(threading.get_ident(), entry.key,
                                                             entry.key.colFamily, entry.value))
            entries += 1

            if entry.key.row not in ret:
                ret[entry.key.row] = {}
                count += 1

            if entry.key.colFamily not in ret[entry.key.row]:
                ret[entry.key.row][entry.key.colFamily] = {}

            ret[entry.key.row][entry.key.colFamily][entry.key.colQualifier] = entry.value
    '''
    except TableNotFoundException:
        log.error("Table not found: {0}".format(config['table']))
        return pd.DataFrame()
    except Exception as err:
        log.error("Accumulo client error: {0}".format(err))
        return pd.DataFrame()
    '''

    log.debug("\t{0}: Read: rows {1}, entries {2}".format(threading.get_ident(), count, entries))

    return pd.DataFrame().from_dict({(i, j): ret[i][j]
                                     for i in ret.keys()
                                     for j in ret[i].keys()}, orient='index')
Beispiel #5
0
from gen import DemoSerivce
from gen.ttypes import DemoObject

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

if __name__ == '__main__':
    # Make socket
    transport = TSocket.TSocket('127.0.0.1', 10000)

    # Buffering is critical. Raw sockets are very slow
    transport = TTransport.TBufferedTransport(transport)

    # Wrap in a protocol
    protocol = TBinaryProtocol.TBinaryProtocol(transport)

    # Create a client to use the protocol encoder
    client = DemoSerivce.Client(protocol)

    # Connect!
    transport.open()

    ping = client.ping("test")
    print ping

    demo_obj = client.getObject("xxx", 2)
    print '%s\t%d' % (demo_obj.x, demo_obj.y)

    # Close!
Beispiel #6
0
def start_extension(name="<unknown>",
                    version="0.0.0",
                    sdk_version="1.8.0",
                    min_sdk_version="1.8.0"):
    """Start your extension by communicating with osquery core and starting
    a thrift server.

    Keyword arguments:
    name -- the name of your extension
    version -- the version of your extension
    sdk_version -- the version of the osquery SDK used to build this extension
    min_sdk_version -- the minimum version of the osquery SDK that you can use
    """
    args = parse_cli_params()

    # Disable logging for the thrift module (can be loud).
    logging.getLogger('thrift').addHandler(logging.NullHandler())

    client = ExtensionClient(path=args.socket)

    if not client.open(args.timeout):
        if args.verbose:
            message = "Could not open socket %s" % args.socket
            raise ExtensionException(
                code=1,
                message=message,
            )
        return
    ext_manager = ExtensionManager()

    # try connecting to the desired osquery core extension manager socket
    try:
        status = client.extension_manager_client().registerExtension(
            info=InternalExtensionInfo(
                name=name,
                version=version,
                sdk_version=sdk_version,
                min_sdk_version=min_sdk_version,
            ),
            registry=ext_manager.registry(),
        )
    except socket.error:
        message = "Could not connect to %s" % args.socket
        raise ExtensionException(
            code=1,
            message=message,
        )

    if status.code is not 0:
        raise ExtensionException(
            code=1,
            message=status.message,
        )

    # Start a watchdog thread to monitor the osquery process.
    rt = threading.Thread(target=start_watcher, args=(client, args.interval))
    rt.daemon = True
    rt.start()

    # start a thrift server listening at the path dictated by the uuid returned
    # by the osquery core extension manager
    ext_manager.uuid = status.uuid
    processor = Processor(ext_manager)

    transport = None
    if sys.platform == 'win32':
        transport = TPipeServer(
            pipe_name="{}.{}".format(args.socket, status.uuid))
    else:
        transport = TSocket.TServerSocket(unix_socket=args.socket + "." +
                                          str(status.uuid))

    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()
    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    server.serve()
Beispiel #7
0
            if len(self.tf_idf_dict) == 0:
                return ''
            sorted_keywords = sorted(self.tf_idf_dict.iteritems(),
                                     key=lambda x: x[1],
                                     reverse=True)
            return json.dumps(sorted_keywords[:nums])
        except Exception, e:
            print e
            logging.error(e)
            return ''


if __name__ == '__main__':
    try:
        handler = KwHandler()
        processor = kwServer.Processor(handler)
        transport = TSocket.TServerSocket(kw_config.IP, kw_config.PORT)

        tfactory = TTransport.TBufferedTransportFactory()
        pfactory = TBinaryProtocol.TBinaryProtocolFactory()
        server = TProcessPoolServer.TProcessPoolServer(processor, transport,
                                                       tfactory, pfactory)
        print "Starting kw server..."
        logging.info("Starting kw server...")
        server.serve()
    except Exception, e:
        print e
        logging.error(e)
    finally:
        print "done!"
Beispiel #8
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Ryan Guhnguk Ahn'


import sys

from hive import ThriftHive
from hive.ttypes import HiveServerException
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

try:
    transport = TSocket.TSocket('localhost', 10000)
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)

    client = ThriftHive.Client(protocol)
    transport.open()

    client.execute("CREATE TABLE r(a STRING, b INT, c DOUBLE)")
    client.execute("LOAD TABLE LOCAL INPATH '/path' INTO TABLE r")
    client.execute("SELECT * FROM r")
    while (1):
      row = client.fetchOne()
      if (row == None):
        break
      print row
    client.execute("SELECT * FROM r")
    def extract(self, img_dir):
        try:
            # Convert unicode to ascci
            ret = extract_featrues(str(img_dir))
            # ret = 'hello'
            # print img_dir
            print ret
            return ret + 'from ' + str(port)
        except:
            print('error ...')


handler = FeatureExtractorHandler()
processor = FeatureExtractor.Processor(handler)

transport = TSocket.TServerSocket(ip, port)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

# server = TServer.TThreadPoolServer(processor,transport,tfactory,pfactory)
server = TNonblockingServer.TNonblockingServer(processor,
                                               transport,
                                               pfactory,
                                               threads=1)
# server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

# from twisted.internet import reactor
# from thrift.transport import TTwisted

# reactor.listenTCP(port, TTwisted.ThriftServerFactory(processor=processor,iprot_factory=pfactory))
# reactor.run()
import sys
sys.path.append("gen-py")
from hola import HolaServicio

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

transporte = TSocket.TSocket("localhost", 9090)
transporte = TTransport.TBufferedTransport(transporte)
protocolo = TBinaryProtocol.TBinaryProtocol(transporte)
cliente = HolaServicio.Client(protocolo)

transporte.open()
mensaje = cliente.hola_func()
print("[Cliente] Se recibio %s" % mensaje)
transporte.close()
Beispiel #11
0
        else:
            return None

    def createDemo(self, demo):
        print "The client invoke method: " + "createDemo."
        demoCache[demo.id] = demo


if __name__ == '__main__':
    handler = DemoServiceHandler()

    # 创建处理器
    processor = DemoService.Processor(handler)

    # 监听端口
    transport = TSocket.TServerSocket("127.0.0.1", "8911")

    # 传输方式工厂:TBufferedTransportFactory/TFramedTransportFactory
    # 服务端使用什么传输方式,客户端就需要使用什么传输方式
    tfactory = TTransport.TFramedTransportFactory()

    # 传输协议工厂:TCompactProtocol/TJSONProtocol/TBinaryProtocol
    # 服务端使用什么传输协议,客户端就需要使用什么传输协议
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    # 创建服务:TSimpleServer/TForkingServer/TThreadedServer/TThreadPoolServer
    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

    print "python thrift server start on 8911"
    server.serve()
Beispiel #12
0
from py.thrift.generated import PersonService, ttypes

from thrift import Thrift
from PersonServerImpl import PersonServerImpl
from thrift.transport import TTransport
from thrift.transport import TSocket
from thrift.protocol import TCompactProtocol
from thrift.server import TServer
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

try:
    PersonServerHandler = PersonServerImpl()
    # 处理器
    processor = PersonService.Processor()
    # 传输通道
    serverSocket = TSocket.TServerSocket(port=8899)
    # 传输格式
    transportFactory = TTransport.TFramedTransportFactory()
    # 传输协议
    protocolFactory = TCompactProtocol.TCompactProtocolFactory()
    # 传输模型
    server = TServer.TSimpleServer(processor, serverSocket, transportFactory,
                                   protocolFactory)
    server.serve()
except Thrift.TException, ex:
    print "%s" % ex.message
Beispiel #13
0
def pandas_write_dataframe(config: dict, data: pd.DataFrame, meta: dict):
    if config['table'] is None:
        log.info("table name cannot be None")
        raise ValueError("Table name cannot be None")

    tid = config['table']
    count = 0

    log.info("PANDAS DATAFRAME: \n{0}".format(data))

    cf = None
    cq = None

    if 'rows' in meta:
        rows = meta['rows']

        if 'cf' in rows:
            cf = rows['cf']
        if 'cq' in rows:
            cq = rows['cq']

    try:
        # create table if it doesnt exist
        create_table(config, tid)

        transport = TSocket.TSocket(config['proxy_host'], config['proxy_port'])
        transport = TTransport.TFramedTransport(transport)
        protocol = TCompactProtocol.TCompactProtocol(transport)
        client = AccumuloProxy.Client(protocol)
        transport.open()

        opt = WriterOptions(maxMemory=1000000, timeoutMs=1000, threads=2)
        lgn = client.login(config['user'], {'password': config['password']})
        wtr = client.createWriter(lgn, tid, opt)

        cells = {}
        attributes = []

        for rid, row in data.iterrows():
            log.debug("Writing row: {0}".format(rid))

            family = row[cf] if cf is not None else None
            qualifier = row[cq] if cq is not None else None

            for col in data.columns:
                if col == cf or col == cq:
                    continue

                family = col if family is None else family
                qualifier = col if qualifier is None else qualifier

                val = json.dumps(row[col], cls=JsonEncode)

                vis = ''
                if 'vis' in config and config['vis'] is not None:
                    if col in config['vis']:
                        vis = str(config['vis'][col])

                ts = time.time()
                if 'ts' in config and config['ts'] is not None:
                    if col in config['ts']:
                        ts = config['ts'][col]

                log.info("Writing kv to {0}: ({1} {2}:{3}, {4}), vis={5}".format(tid, rid, family, qualifier, val, vis))
                attributes.append(ColumnUpdate(colFamily=str(family),
                                               colQualifier=str(qualifier),
                                               colVisibility=str(vis),
                                               timestamp=int(ts),
                                               value=str(val)))

                ### Cant just jam these into cells by rid.. need to use rid + cf + cq
                
            # cells[str(rid)] = attributes
            cells.append(attributes)
            attributes = []

            count = count + 1

        client.updateAndFlush(lgn, tid, cells)
        client.closeWriter(wtr)
        transport.close()
    except TableNotFoundException:
        log.error("Table not found: {0}".format(tid))
    except Exception as err:
        log.error("Accumulo client error: {0}".format(err))

    return count
Beispiel #14
0
 def open(self):
     socket = TSocket.TSocket(self.host, self.port)
     self.transport = TTransport.TBufferedTransport(socket)
     protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
     self.client = Hbase.Client(protocol)
     self.transport.open()
from thrift.protocol import TBinaryProtocol

# Add path for local "gen-py/hbase" for the pre-generated module
gen_py_path = os.path.abspath('gen-py')
sys.path.append(gen_py_path)
from hbase import THBaseService
from hbase.ttypes import *

print "Thrift2 Demo"
print "This demo assumes you have a table called \"example\" with a column family called \"family1\""

host = "localhost"
port = 9090
framed = False

socket = TSocket.TSocket(host, port)
if framed:
    transport = TTransport.TFramedTransport(socket)
else:
    transport = TTransport.TBufferedTransport(socket)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = THBaseService.Client(protocol)

transport.open()

table = "example"

put = TPut(row="row1",
           columnValues=[
               TColumnValue(family="family1",
                            qualifier="qualifier1",
Beispiel #16
0
        try:
            server = THttpServer.THttpServer(
                    processor, ('', options.port), pfactory)
        except:
            print("Could not load THttpServer")
            raise
    elif args[0] == "TCppServer":
        server = TCppServer.TCppServer(processor)
        server.setPort(options.port)
    else:
        if options.ssl:
            cert_path = 'thrift/test/py/test_cert.pem'
            transport = TSSLSocket.TSSLServerSocket(options.port,
                    certfile=cert_path)
        else:
            transport = TSocket.TServerSocket(options.port)
        tfactory = TTransport.TBufferedTransportFactory()

        server_class_name = args[0]

        if args[0] == "TNonblockingServer":
            server = TNonblockingServer.TNonblockingServer(
                    processor, transport, pfactory,
                    readTimeout=options.timeout)
        elif args[0] == "TProcessPoolServer":
            server = TProcessPoolServer.TProcessPoolServer(
                    processor, transport, tfactory, pfactory)
        else:
            ServerClass = getattr(TServer, server_class_name)
            server = ServerClass(processor, transport, tfactory, pfactory)
Beispiel #17
0
def connect():
    switchtime = 58
    totaltime = 60
    p4_client_module = importlib.import_module("p4_pd_rpc." + p4_name)
    transport = TSocket.TSocket("localhost", 9090)
    bprotocol = TBinaryProtocol.TBinaryProtocol(transport)

    p4_protocol = TMultiplexedProtocol.TMultiplexedProtocol(bprotocol, p4_name)
    client = p4_client_module.Client(p4_protocol)
    pal_protocol = TMultiplexedProtocol.TMultiplexedProtocol(bprotocol, "pal")
    pal_client_module = importlib.import_module(".".join(["pal_rpc", "pal"]))
    conn_mgr_client_module = importlib.import_module('.'.join(
        ['conn_mgr_pd_rpc', 'conn_mgr']))
    conn_mgr_protocol = TMultiplexedProtocol.TMultiplexedProtocol(
        bprotocol, 'conn_mgr')
    conn_mgr = conn_mgr_client_module.Client(conn_mgr_protocol)

    transport.open()

    pal = pal_client_module.Client(pal_protocol)
    dev_id = 0
    ports = [0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60]
    pal.pal_port_del_all(dev_id)
    for port in ports:
        pal.pal_port_add(dev_id, port, pal_port_speed_t.BF_SPEED_40G,
                         pal_fec_type_t.BF_FEC_TYP_NONE)
    pal.pal_port_enable_all(dev_id)
    sess_hdl = conn_mgr.client_init()
    dev_tgt = DevTarget_t(0, int(0xFFFF) - 0x10000)

    for kv in iphash2port:
        match_spec = flowSF_ECMP_t_match_spec_t(ipv4Addr_to_i32(kv[0]), kv[1])
        action_spec = flowSF_ECMP_action_spec_t(kv[2])
        try:
            client.ECMP_t_table_delete_by_match_spec(sess_hdl, dev_tgt,
                                                     match_spec)
        except:
            pass
        client.ECMP_t_table_add_with_ECMP(sess_hdl, dev_tgt, match_spec,
                                          action_spec)

    for kv in s:
        priority = 0
        match_spec = flowSF_offset_match_spec_t(kv[0], kv[1])
        action_spec = flowSF_os_action_spec_t(kv[2], kv[3])
        try:
            client.offset_table_delete_by_match_spec(sess_hdl, dev_tgt,
                                                     match_spec)
        except:
            pass
        client.offset_table_add_with_os(sess_hdl, dev_tgt, match_spec,
                                        priority, action_spec)
    print "Port add done."

    pr = 255
    match_spec = flowSF_take_t_match_spec_t(2)
    client.take_t_table_add_with_write2(sess_hdl, dev_tgt, match_spec)
    match_spec = flowSF_take_t_match_spec_t(1)
    client.take_t_table_add_with_write1(sess_hdl, dev_tgt, match_spec)

    for kv in r:
        match_spec = flowSF_getgoodsign_match_spec_t(kv[0], kv[1])
        action_spec = flowSF_ggs_action_spec_t(kv[2])
        client.getgoodsign_table_add_with_ggs(sess_hdl, dev_tgt, match_spec,
                                              action_spec)

    match_spec1 = flowSF_rdmz_match_spec_t(0)
    match_spec2 = flowSF_rdmz_match_spec_t(1)
    match_spec3 = flowSF_rdmz_match_spec_t(2)
    match_spec4 = flowSF_rdmz_match_spec_t(3)
    client.rdmz_table_add_with_rm1(sess_hdl, dev_tgt, match_spec2)
    client.rdmz_table_add_with_rm1(sess_hdl, dev_tgt, match_spec4)
    client.rdmz_table_add_with_rm2(sess_hdl, dev_tgt, match_spec1)
    client.rdmz_table_add_with_rm2(sess_hdl, dev_tgt, match_spec3)

    match_spec1 = flowSF_restore_match_spec_t(0)
    match_spec2 = flowSF_restore_match_spec_t(1)
    match_spec3 = flowSF_restore_match_spec_t(2)
    match_spec4 = flowSF_restore_match_spec_t(3)
    client.restore_table_add_with_rs1(sess_hdl, dev_tgt, match_spec2)
    client.restore_table_add_with_rs1(sess_hdl, dev_tgt, match_spec4)
    client.restore_table_add_with_rs2(sess_hdl, dev_tgt, match_spec1)
    client.restore_table_add_with_rs2(sess_hdl, dev_tgt, match_spec3)

    sign = 1
    match_spec = flowSF_sign_t_match_spec_t(0)
    action_spec = flowSF_signing_action_spec_t(sign)
    try:
        client.sign_t_table_delete_by_match_spec(sess_hdl, dev_tgt, match_spec)
    except:
        pass
    client.sign_t_table_add_with_signing(sess_hdl, dev_tgt, match_spec,
                                         action_spec)
    '''considersleep'''
    time1 = datetime.datetime.now()
    x = 0
    y = 0
    z = 0
    while True:
        time2 = datetime.datetime.now()
        if (time2 - time1).total_seconds() >= switchtime and x == 0:
            print((time2 - time1).total_seconds())
            sign1 = (sign + 2) % 4
            x = 1
            match_spec = flowSF_sign_t_match_spec_t(0)
            action_spec = flowSF_signing_action_spec_t(sign1)
            try:
                client.sign_t_table_delete_by_match_spec(
                    sess_hdl, dev_tgt, match_spec)
            except:
                pass
            client.sign_t_table_add_with_signing(sess_hdl, dev_tgt, match_spec,
                                                 action_spec)
            time.sleep(0.1)
            client.register_reset_all_rm_a(sess_hdl, dev_tgt)
            if sign1 == 3:
                client.register_reset_all_fs_a_1_1(sess_hdl, dev_tgt)
                client.register_reset_all_fs_a_1_2(sess_hdl, dev_tgt)
                client.register_reset_all_fs_b_1_1(sess_hdl, dev_tgt)
                client.register_reset_all_fs_b_1_2(sess_hdl, dev_tgt)
                print("clean sketch1")
            if sign1 == 0:
                client.register_reset_all_fs_a_2_1(sess_hdl, dev_tgt)
                client.register_reset_all_fs_a_2_2(sess_hdl, dev_tgt)
                client.register_reset_all_fs_b_2_1(sess_hdl, dev_tgt)
                client.register_reset_all_fs_b_2_2(sess_hdl, dev_tgt)
                print("clean sketch2")
            time6 = datetime.datetime.now()
            print((time6 - time2).total_seconds())
        if (time2 - time1).total_seconds() >= totaltime:
            print((time2 - time1).total_seconds())
            z = 1
            time1 = time2
            sign = 3 - sign
            x = 0
            y = 0
            match_spec = flowSF_sign_t_match_spec_t(0)
            action_spec = flowSF_signing_action_spec_t(sign)
            try:
                client.sign_t_table_delete_by_match_spec(
                    sess_hdl, dev_tgt, match_spec)
            except:
                pass
            client.sign_t_table_add_with_signing(sess_hdl, dev_tgt, match_spec,
                                                 action_spec)
Beispiel #18
0
from mudserve.combat.handler import CombatHandler
from mudserve.mudrpc.combat import CombatService

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

PORT = 9090

handler = CombatHandler()
processor = CombatService.Processor(handler)
transport = TSocket.TServerSocket(PORT)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TForkingServer(processor, transport, tfactory, pfactory)

print "Starting the server on port %i..." % (PORT)
server.serve()
print "done."
Beispiel #19
0
                                                 self.position.z,
                                                 self.position.alfa)
    sleep(0.5)
    return True

  def getCurrentDevice(self):
    return "android"

  def setDevice(self, device):
    print "Selecting device name {}".format(device)
    sleep(10)
    return True

  def reloaddutconfig(self, idx):
    print "Reload config for dut {}".format(idx)
    return

if __name__ == "__main__":
  handler   = RataServiceHandler()
  processor = rataservice.Processor(handler)
  transport = TSocket.TServerSocket(port=9090)
  tfactory  = TTransport.TFramedTransportFactory()
  pfactory  = TBinaryProtocol.TBinaryProtocolFactory()
  server    = TServer.TThreadedServer(processor, transport, tfactory, pfactory)

  print "Server started"
  try:
    server.serve()
  except KeyboardInterrupt:
    os.kill(os.getpid(), signal.SIGKILL)
Beispiel #20
0
		elif tag == 'cat':
			puntero.execute("SELECT name FROM gifs WHERE tag = 'cat' ORDER BY popularidad DESC LIMIT 10")
		elif tag == 'sports':
			puntero.execute("SELECT name FROM gifs WHERE tag = 'sports' ORDER BY popularidad DESC LIMIT 10")

		lista_gifs = []
		for x in puntero:
			res = (requests.get(x[0])).content
        		self.r.sadd(tag, res)
			lista_gifs.append(res)
		self.r.expire(tag, 60)
		return lista_gifs



if __name__ == '__main__':
	try:
		handler = GifsvHandler()
		processor = Gifsv.Processor(handler)
		transport = TSocket.TServerSocket(host='127.0.0.1', port=9999)
		tfactory = TTransport.TBufferedTransportFactory()
		pfactory = TBinaryProtocol.TBinaryProtocolFactory()

		server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)
		print('Its dangerous go alone')
		print('Take this server')
		server.serve()
		logging.basicConfig(level=logging.DEBUG)
	except:
		print("error")
Beispiel #21
0
 def __init__(self, class_, host, port):
     self.transport = TSocket.TSocket(host, port)
     protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
     self.client = class_.Client(protocol)
     self.transport.open()
Beispiel #22
0
# -*- coding:utf-8 -*-
import sys
sys.path.append('/usr/local/hadoop/hive/lib/py')
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
from thrift.transport import TTransport
from hbase import THBaseService

transport = TTransport.TBufferedTransport(TSocket.TSocket('127.0.0.1', 9090))
protocol = TBinaryProtocol.TBinaryProtocolAccelerated(transport)
client = THBaseService.Client(protocol)
transport.open()
# 使用 client 实例进行操作
# transport.close()
Beispiel #23
0
            exception.code = 404
            exception.mesage = 'Task not found'
            raise exception

        task = TaskHandler.convertInstance(instance)
        return task

    @staticmethod
    def convertInstance(instance):
        task = Task()
        task.id = str(instance['_id'])
        task.userId = instance['userId']
        task.name = instance['name']
        task.createdOn = instance['createdOn'].isoformat()
        task.done = instance['done']
        return task


if __name__ == '__main__':
    port = 6000
    handler = TaskHandler()
    processor = Tasks.Processor(handler)
    transport = TSocket.TServerSocket(port=port)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

    print('main')
    server.serve()
Beispiel #24
0
# Talk to a server via TCP sockets, using a binary protocol
from thrift.transport.TSocket import *
from thrift.protocol.TBinaryProtocol import *
from pylib.echo import *
transport = TSocket("localhost", 9090)
transport.open()
protocol = TBinaryProtocol(transport)

# Use the service we already defined
service = EchoService.Client(protocol)
returnValue = service.echo("Hello World!")
print returnValue
from message.api import MessageService
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer


class MessageServiceHandler:
    def sendMobileMessage(self):
        print("sendMobileMessage")
        return True

    def sendEmailMessage(self):
        print("sendEmailMessage")
        return True


if __name__ == "__main__":
    handler = MessageServiceHandler()
    processor = MessageService.Processor(handler)
    transport = TSocket.TServerSocket(host="0.0.0.0", port=8800)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    print("python thrift server start")
    server.serve()
    print("python thrift server exit")