Exemple #1
0
def main():
    ip = "0"
    port = 9090
    server = make_server(interface_thrift.Suggestion, PredictHandler(), ip,
                         port)
    print("serving...", ip, port)
    server.serve()
Exemple #2
0
def jvs_server():
    return make_server(
        jvs_thrift.JvsService,
        JvsService(),
        config.JVS_THRIFT_SERVICE['host'],
        config.JVS_THRIFT_SERVICE['port'],
    )
Exemple #3
0
def main():

    parser = argparse.ArgumentParser(
        description="Ratchet Thrift Server"
    )

    parser.add_argument(
        '--address',
         '-a',
        default=ADDRESS,
        help='Binding address (%s)' % ADDRESS
    )

    parser.add_argument(
        '--port',
        '-p',
        default=PORT,
        help='Binding port (%s)' % PORT
    )

    args = parser.parse_args()

    ratchet_controller = Ratchet(settings['app:main']['mongo_uri'])

    dispatcher = Dispatcher(ratchet_controller)

    server = make_server(ratchet_thrift.RatchetStats, dispatcher, args.address, args.port)

    logger.info('Starting Thrift RPC Server at %s:%s.' % (args.address, args.port))

    server.serve()
Exemple #4
0
def serve(thrift_filename,
          service_name,
          contract_filename,
          host="127.0.0.1",
          port=6000,
          protocol=Protocol.binary,
          transport=Transport.framed):
    # Loads both the AST and the thriftpy dynamically generated data
    ast = ptcdt.thrift_parser.MappedAST.from_file(thrift_filename)
    thriftpy_module = thriftpy.load(thrift_filename,
                                    module_name=service_name + "_thrift")
    contract = ptcdt.contracts.parse_contract(contract_filename)

    # Builds the delegate class which will have all the methods to handle the requests
    # The delegate will have the methods dynamically added into them, which actually point
    # to methods in a new instance of FunctionDelegate objects
    Delegate = build_delegate(
        _ServiceExecutionContext(ast, thriftpy_module, contract, service_name))

    # Builds the server and starts serving requests
    server = make_server(service=getattr(thriftpy_module, service_name),
                         handler=Delegate(),
                         host=host,
                         port=port,
                         proto_factory=_build_protocol_factory(protocol),
                         trans_factory=_build_transport_factory(transport))

    server.serve()
 def run_server(self, local_server, port):
     server = make_server(pepi_thrift.CameraServer, local_server,
                          '127.0.0.1', port)
     t = threading.Thread(target=server.serve)
     t.daemon = True
     t.start()
     return None
Exemple #6
0
def main():
    server = make_server(calc_thrift.Calculator, Dispatcher(),
                         '127.0.0.1', 6000,
                         proto_factory=TCyBinaryProtocolFactory(),
                         trans_factory=TCyBufferedTransportFactory())
    print("serving...")
    server.serve()
Exemple #7
0
def ps_job(ps_id, cluster_spec, dim):
    signal.signal(signal.SIGINT, soft_exit)
    ping_thrift = thriftpy.load("ping.thrift", module_name="ping_thrift")
    handler = Dispatcher(dim)
    server = make_server(ping_thrift.PingService, handler, '127.0.0.1', 6000)
    print "start Server(%s:%d)" % ('127.0.0.1', 6000)
    server.serve()
 def mk_server(self):
     server = make_server(addressbook.AddressBookService, Dispatcher(),
                          host="localhost", port=self.PORT,
                          proto_factory=self.PROTOCOL_FACTORY,
                          trans_factory=self.TRANSPORT_FACTORY)
     p = multiprocessing.Process(target=server.serve)
     return p
Exemple #9
0
def main():
    server = make_server(calc.Calculator,
                         Dispatcher(),
                         '127.0.0.1',
                         6000,
                         proto_factory=TCyBinaryProtocolFactory())
    print("serving...")
    server.serve()
Exemple #10
0
def main():
    server = make_server(tutorial.Calculator,
                         CalculatorHandler(),
                         '127.0.0.1',
                         6000,
                         proto_factory=TCyBinaryProtocolFactory())
    print("serving...")
    server.serve()
Exemple #11
0
def main():
    server = make_server(calc_thrift.Calculator,
                         Dispatcher(),
                         '127.0.0.1',
                         6000,
                         proto_factory=TCyBinaryProtocolFactory(),
                         trans_factory=TCyBufferedTransportFactory())
    print("serving...")
    server.serve()
 def mk_server(self):
     server = make_server(addressbook.AddressBookService,
                          Dispatcher(),
                          host="localhost",
                          port=self.PORT,
                          proto_factory=self.PROTOCOL_FACTORY,
                          trans_factory=self.TRANSPORT_FACTORY)
     p = multiprocessing.Process(target=server.serve)
     return p
Exemple #13
0
def serve(port, server='0.0.0.0'):
    """
    Run as a thrift service (interpreter)

    Args:
        port (int): the port to listen on
        server (str): ip to bind to (default: 0.0.0.0)
    """
    server = make_server(lang_thrift.CodeExecutor, Dispatcher(), server, port)
    server.serve()
Exemple #14
0
def init_receiver(ip, port, requestHandler):
    if not os.path.exists("weightsync.thrift"):
        f = _get_thrift_file()
        weightsync_thrift = thriftpy.load(f.name, module_name="weightsync_thrift")
        f.close()
    else:
        weightsync_thrift = thriftpy.load("weightsync.thrift", module_name="weightsync_thrift")
    receiver = make_server(weightsync_thrift.WeightForward, requestHandler, ip, port)
    receiver.trans.client_timeout = None
    return receiver
def init_server(ip, port, requestHandler):
    if not os.path.exists("weightsync.thrift"):
        f = _get_thrift_file()
        weightsync_thrift = thriftpy.load(f.name,
                                          module_name="weightsync_thrift")
        f.close()
    else:
        weightsync_thrift = thriftpy.load("weightsync.thrift",
                                          module_name="weightsync_thrift")
    server = make_server(weightsync_thrift.WeightSync, requestHandler, ip,
                         port)
    return server
Exemple #16
0
def ssl_server(request):
    ssl_server = make_server(addressbook.AddressBookService, Dispatcher(),
                             host='localhost', port=SSL_PORT,
                             certfile="ssl/server.pem")
    ps = multiprocessing.Process(target=ssl_server.serve)
    ps.start()

    time.sleep(0.1)

    def fin():
        if ps.is_alive():
            ps.terminate()
    request.addfinalizer(fin)
Exemple #17
0
def ssl_server(request):
    ssl_server = make_server(addressbook.AddressBookService, Dispatcher(),
                             host='localhost', port=SSL_PORT,
                             certfile="ssl/server.pem")
    ps = multiprocessing.Process(target=ssl_server.serve)
    ps.start()

    time.sleep(0.1)

    def fin():
        if ps.is_alive():
            ps.terminate()
    request.addfinalizer(fin)
Exemple #18
0
def serve_forever(runtime, port, client):
    try:
        api_details = import_module(runtime.entrypoint)
        r = client.post("http://okapi-engine:5000/okapi/service/v1/%s/%s/spec" % (runtime.service_name, runtime.service_version), json = api_details)
        logging.debug("post service spec status: %s" % r.status_code)
    except:
        traceback.print_exc()
    try:
        logging.info("start to serve on port %s" % port)
        server = make_server(okapi_thrift.InvokeService, Dispatcher(), '0.0.0.0', port, trans_factory=TFramedTransportFactory())
        server.serve()
    except Exception as e:
        traceback.print_exc()
        sys.exit(2)  # serve fails (e.g. port already used) or serve exited (e.g. user press CTRL+C)
  def __init__(self):
    # We need to run a FrontendService server, even though it does nothing in
    # practice
    fes = make_server(sparrow_service_thrift.FrontendService,
                      FLAGS.sparrow_frontend_host, FLAGS.sparrow_frontend_port,
                      trans_factory=tf)
    self.scheduler_client = make_client(sparrow_service_thrift.SchedulerService,
                                        FLAGS.sparrow_scheduler_host,
                                        FLAGS.sparrow_scheduler_port,
                                        trans_factory=tf)

    self.scheduler_client.registerFrontend("clusterMixApp",
                                           FLAGS.sparrow_frontend_host + ":" +
                                           str(FLAGS.sparrow_frontend_port))
Exemple #20
0
def server(request):
    server = make_server(addressbook.AddressBookService, Dispatcher(),
                         unix_socket="./thriftpy_test.sock")
    ps = multiprocessing.Process(target=server.serve)
    ps.start()

    time.sleep(0.1)

    def fin():
        if ps.is_alive():
            ps.terminate()
        try:
            os.remove("./thriftpy_test.sock")
        except IOError:
            pass
    request.addfinalizer(fin)
Exemple #21
0
def server(request):
    server = make_server(addressbook.AddressBookService, Dispatcher(),
                         unix_socket=unix_sock)
    ps = multiprocessing.Process(target=server.serve)
    ps.start()

    time.sleep(0.1)

    def fin():
        if ps.is_alive():
            ps.terminate()
        try:
            os.remove(unix_sock)
        except IOError:
            pass
    request.addfinalizer(fin)
Exemple #22
0
 def __init__(self, metadata: MetadataProvider, pubsub: PubSubProvider,
              db: DbProvider, cv: CvProvider, media: MediaProvider,
              apiv3: ApiV3Provider):
     logging.info("Creating gdcv thrift handler...")
     gdcv_thrift = thriftpy.load(
         'if/gdcv.thrift', module_name='gdcv_thrift')
     dispatch = FrcRealtimeScoringServiceHandler(
         version=self.VERSION,
         thrift=gdcv_thrift,
         metadata=metadata,
         pubsub=pubsub,
         db=db,
         cv=cv,
         media=media,
         apiv3=apiv3,
     )
     self.server = make_server(
         gdcv_thrift.FrcRealtimeScoringService,
         dispatch,
         self.BIND_ADDR,
         self.BIND_PORT
     )
Exemple #23
0
def do_serve(host, port):

    print "Starting thrift server on %s:%s..." % (host, port)

    try:
        server = make_server(
            tracelogs_thrift.TraceLogService,
            TracesThriftServerController(module=tracelogs_thrift),
            host, port,
            proto_factory=TCyBinaryProtocolFactory(),
            trans_factory=TCyBufferedTransportFactory()
        )

        server.serve()

    except thriftpy.thrift.TException as ex:
        logger.error('Thrift error: %s' % ex.message)

    except socket_error as sex:
        logger.error('Network error: %s' % sex)

    except Exception as ex:
        logger.error('Application error: %s' % ex)
        raise
Exemple #24
0
def main():
    server = make_server(
        tutorial.Calculator, CalculatorHandler(), '127.0.0.1', 6000,
        proto_factory=TCyBinaryProtocolFactory())
    print("serving...")
    server.serve()
Exemple #25
0
def main_pong():
    # 定义监听的端口和服务
    server = make_server(pp_thrift.PingService, Dispatcher(), '127.0.0.1', 24680)
    print("serving...")
    server.serve()
Exemple #26
0
def start_trade_server(thrift_file="traderpc.thrift"):
    trade_thrift = thriftpy.load(thrift_file, module_name="trade_thrift")
    print('trade server running...')
    server = make_server(trade_thrift.TradeRpcService, TradeServer(), '0.0.0.0', 24680, client_timeout=30000)
    server.serve()
    print('trade server stopped')
Exemple #27
0
def listen():
    server = make_server(enqueue_thrift.RPC,
                         QueueHandler(), master_ip, master_port)
    server.serve()
Exemple #28
0
def main():
    server = make_server(tutorial_thrift.Calculator, CalculatorHandler(),
                         '127.0.0.1', 6000)
    print("serving...")
    server.serve()
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import thriftpy
from thriftpy.rpc import make_server
import os

class MyRPC(object):
    # 提供调用的方法
    def print_fun(self,name):
        str = "Hello " + name
        return str

if __name__ == "__main__":
    file_path = os.path.abspath("../conf/simple.thrift")
    # 加载注册文件
    simple_thrift = thriftpy.load(file_path, module_name="simple_thrift")

    server = make_server(simple_thrift.RPCTest, MyRPC(), '192.168.1.105', 6000)
    print "Thriftpy listening 6000......"
    server.serve()
def server_start(conf_path, server_ip, server_port):
    # 加载注册文件
    file_thrift = thriftpy.load(conf_path, module_name="file_thrift")
    server = make_server(file_thrift.FileRPC, MyFileRPC(), server_ip, server_port)
    print "Thriftpy listening " + str(server_port) + "......"
    server.serve()
Exemple #31
0
def fun_rpc_server(args):
    print('fun_rpc_server  start!')
    print(ip, port)
    server = make_server(endpoint_service.endpointControl, Dispatcher(), ip,
                         port)
    server.serve()
Exemple #32
0
from open.settings import BASE_DIR
import thriftpy
from thriftpy.rpc import make_server
import os
import logging


ZK_SMARTSYS_ONLINE = ZookeeperHandler(ZK_HOSTS, SMARTSYS_ONLINE)
SERVICES_ONLINE = ZK_SMARTSYS_ONLINE.discover()
THRIFT_ONLINE = thriftpy.load(os.path.join(BASE_DIR, "idl/online.thrift"), module_name="device_online_service_thrift")


class Online(object):
    def ping(self):
        return "pong"
    def get_status(self,device_id):
        ret = {'msg': '请求成功', 'data': 'online', 'code': '0'}
        return ret

ret = SERVICES_ONLINE
if len(ret) < 1:
    # pass
    raise Exception("没有可用的服务:%s" % SERVICES_ONLINE)
# 随机方式实现负载均衡
s = ret[randint(0, len(ret) - 1)].split(":")
# server_addr = s[0]
# server_port = int(s[1])
server_addr = "127.0.0.1"
server_port = 6000
server = make_server(THRIFT_ONLINE.Device, Online(), server_addr, server_port)
server.serve()
import thriftpy
from thriftpy.rpc import make_server
import math

sv_thrift = thriftpy.load('service.thrift', module_name='sv_thrift')

class Dispatcher:
    def ping(self, x):
        return 'Ping~{0}'.format(math.exp(x))

ip = '127.0.0.1'
port = 6666
server = make_server(sv_thrift.Ping, Dispatcher(), ip, port)
server.serve()

Exemple #34
0
 def serve(cls, config):
     dispatcher = cls()
     server = make_server(Allocations, dispatcher, **config['thrift'])
     server.serve()
Exemple #35
0
from thriftpy import load
from thriftpy.rpc import make_server
from thriftpy.transport import TFramedTransportFactory

echo_thrift = load("/app/sh/echo.thrift", module_name="echo_thrift")


class echoHandler(object):
    def echo(self, msg):
        return msg.text


make_server(
    service=echo_thrift.Echo,
    handler=echoHandler(),
    host="127.0.0.1",
    port=9999,
    trans_factory=TFramedTransportFactory(),
).serve()
Exemple #36
0
def main():
    server = make_server(calc.Calculator, Dispatcher(), '127.0.0.1', 6000,
                         proto_factory=TCyBinaryProtocolFactory())
    print("serving...")
    server.serve()
Exemple #37
0
import time

import thriftpy
from thriftpy.rpc import make_server


class Dispatcher(object):
    def get_time(self):
        return time.ctime()


time_thrift = thriftpy.load('time_service.thrift', module_name='time_thrift')
server = make_server(time_thrift.TimeService, Dispatcher(), '127.0.0.1', 6000)
server.serve()
Exemple #38
0
def listen(port=9090):
    server = make_server(dequeue_thrift.RPC, Worker(ip, port), ip, port)
    server.serve()
Exemple #39
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Author: stdrickforce (Tengyuan Fan)
# Email: <*****@*****.**> <*****@*****.**>

import thriftpy

from thriftpy.rpc import make_server

ping_thrift = thriftpy.load("./ping.thrift", module_name='ping_thrift')


class Dispatcher(object):
    def __init__(self):
        self.logs = {}

    def ping(self):
        print("ping request")

    def foo(self, v_i16, v_bool, v_i32, v_str, v_list, v_set, v_map, v_st,
            v_st_map):
        print(v_i16, v_bool, v_i32, v_str, v_list, v_set, v_map, v_st)
        for key, val in v_st_map.items():
            print(key, val)


server = make_server(ping_thrift.Ping, Dispatcher(), "0.0.0.0", 6000)
print("server is listening on :6000")
server.serve()


"""

pingpong.thrift
---------------

service PingPong {
    string ping(),
}
"""


import thriftpy
pingpong_thrift = thriftpy.load("pingpong.thrift", module_name="pingpong_thrift")

from thriftpy.rpc import make_server

class Dispatcher(object):
    def ping(self):
        return "pong"

server = make_server(pingpong_thrift.PingPong, Dispatcher(), '127.0.0.1', 6000)
server.serve()
Exemple #41
0
Fichier : main.py Projet : 12z/Raft
def start_server():
    server = make_server(thrift_service.Ping, Dispatcher(), 'localhost', 9001)
    print('serving..')
    server.serve()
Exemple #42
0
# In The Name Of God
# ========================================
# [] File Name : server.py
#
# [] Creation Date : 11-10-2016
#
# [] Created By : Parham Alvani ([email protected])
# =======================================
import thriftpy
from thriftpy.rpc import make_server

watraft_thrift = thriftpy.load("WatRaft.thrift", module_name="watraft_thrift")


class Dispatcher:
    def get(self, key: str):
        return "Amusse you get the value of %s" % key

    def put(self, key: str, val: str):
        return "Ammuse %s is put into %s" % (value, key)

    def append_entries(self, term: int, leader_id: int,
                       prev_log_index: int, prev_log_temr: int,
                       entries: list, leader_commit_index: int):
        return "You take this shit seriously"

server = make_server(watraft_thrift.WatRaft, Dispatcher(), '127.0.0.1', 6000)
server.serve()
Exemple #43
0
def main():
    server = make_server(pp_thrift.PingService, Dispatcher(),
                         '127.0.0.1', 6000)
    print("serving...")
    server.serve()
Exemple #44
0
def jvs_server():
    return make_server(
        jvs_thrift.JvsService, JvsService(),
        config.JVS_THRIFT_SERVICE['host'],
        config.JVS_THRIFT_SERVICE['port'],
    )
Exemple #45
0
        print(instance)
        if (instance is None):
            exception = tasks.BaseException()
            exception.code = 404
            exception.message = 'Task not found'
            raise exception

        task = TaskHandler.convertInstance(instance)
        return task

    @staticmethod
    def convertInstance(instance):
        task = tasks.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

host = Config.getTaskServiceConfig()['host']
port = Config.getTaskServiceConfig()['port']

print('Server is running on %s port %d' % (host, port))
server = make_server(tasks.Tasks,
                    TaskHandler(),
                    host,
                    port)
server.serve()
Exemple #46
0
import thriftpy

pingpong_thrift = thriftpy.load("pingpong.thrift", module_name="pingpong_thrift")

from thriftpy.rpc import make_server


class Dispatcher(object):
    def ping(self):
        return "pong"


server = make_server(pingpong_thrift.PingPong, Dispatcher(), '127.0.0.1', 6000)
server.serve()
Exemple #47
0
            return json.dumps(to_send)
        except fs.FileNotFound as e:
            to_send['err'] = str(e)
            return json.dumps(to_send)
        else:
            to_send['err'] = 'An unexpected error occurred'
            return json.dumps(to_send)


#Signal handler to ensure that on a termination signal, the file store saves
#the state of the system. Probably don't need this anymore.
def signal_handler(signal, frame):
    sys.exit(0)  #And now its watch has ended


signal.signal(signal.SIGTERM,
              signal_handler)  #Really, this is just like signing a will

#Starts the thrift service running on port 6000
#Remember, use 127.0.0.1 and not localhost. We still want to avoid the apocalypse!
server = make_server(link_thrift.Link,
                     Dispatcher(),
                     '127.0.0.1',
                     6000,
                     proto_factory=TCyBinaryProtocolFactory(),
                     trans_factory=TCyBufferedTransportFactory())
print("Service activated")
server.serve()

finished = True
Exemple #48
0
import thriftpy
test_thrift = thriftpy.load("benchmarkmessage.thrift",
                            module_name="test_thrift")

from thriftpy.rpc import make_server


class Dispatcher(object):
    def echo(self, message):
        return message


server = make_server(test_thrift.Helloworld, Dispatcher(), '127.0.0.1', 6000)
server.serve()
Exemple #49
0
class Dispatcher(object):
    def initialize(self, initList):
        print 'here'
        initList = pickle.loads(initList)
        self.models = []

        for dim in initList:
            self.models.append(LinearModel(dim[0], dim[1], dim[2]))

        print self.models

    def predict(self, h, id):
        id = int(id)
        currModel = self.models[id]  # by id
        h_val = pickle.loads(h)
        syn_gradient = currModel.get_syn_gradients(np.mean(h_val, axis=0))
        return pickle.dumps(syn_gradient, protocol=0)

    def update(self, trueGrad, id):
        id = int(id)
        currModel = self.models[id]
        trueGrad_val = pickle.loads(trueGrad)
        # print trueGrad_val
        currModel.update_model(trueGrad_val)


server = make_server(linear_thrift.LinearModel, Dispatcher(), '127.0.0.1',
                     6010)
server.serve()
Exemple #50
0
def main():
    server = make_server(pp_thrift.PingService, Dispatcher(), '127.0.0.1',
                         6000)
    print("serving...")
    server.serve()
Exemple #51
0
def main():
    server = make_server(sleep_thrift.Sleep, Dispatcher(),
                         '127.0.0.1', 6000)
    print("serving...")
    server.serve()
Exemple #52
0
def serve():
    server = make_server(addressbook.AddressBookService, Dispatcher(),
                         '127.0.0.1', 8000)
    server.serve()
Exemple #53
0
def main():
    server = make_server(sleep_thrift.Sleep, Dispatcher(),
                         '127.0.0.1', 6000)
    print("serving...")
    server.serve()