def get_status(self): cli = msgpackrpc.Client(msgpackrpc.Address('127.0.0.1', self.port), unpack_encoding='utf-8') try: return cli.call('get_status', '')['127.0.0.1_{0}'.format(self.port)] finally: cli.close()
def reset_level(self): self.client.call("OpenHighway") self.client.close() del self.client time.sleep(10) self.client = msgpackrpc.Client(msgpackrpc.Address(self.host, \ self.port), timeout = 5, \ pack_encoding = 'utf-8', unpack_encoding = 'utf-8')
def __init__(self, ip="", port=41451, timeout_value=3600): if (ip == ""): ip = "127.0.0.1" self.client = msgpackrpc.Client(msgpackrpc.Address(ip, port), timeout=timeout_value, pack_encoding='utf-8', unpack_encoding='utf-8') self.battery = BatteryState()
def move_drone(self, origin_pos, next_pos, speed): log.info("move drone in mininet") rel_x, rel_y, rel_z = (origin_pos.x_val - next_pos.x_val, origin_pos.y_val - next_pos.y_val, origin_pos.z_val - next_pos.z_val) myrpcclient = msgpackrpc.Client( msgpackrpc.Address(self.server_ip, self.server_port)) myrpcclient.call('move', time.time(), rel_x, rel_y, rel_z, speed)
def __init__(self, ip="", port=41451, timeout_value=30): if (ip == ""): self.ip = "127.0.0.1" else: self.ip = ip self.client = msgpackrpc.Client(msgpackrpc.Address(ip, port), timeout=timeout_value, pack_encoding='utf-8', unpack_encoding='utf-8')
def run_notify(): client = msgpackrpc.Client(msgpackrpc.Address("localhost", 18800)) before = time.time() for x in range(Num): client.notify('sum', 1, 2) after = time.time() diff = after - before print("notify: {0} qps".format(Num / diff))
def __init__(self, ip='', port=41451, timeout_value=1000,): if ip == '': ip = '127.0.0.1' self.client = msgpackrpc.Client(msgpackrpc.Address(ip, port), timeout=timeout_value, pack_encoding='utf-8', unpack_encoding='utf-8')
def run_call(): client = msgpackrpc.Client(msgpackrpc.Address("localhost", 18800), timeout=20) before = time.time() for x in range(Num): client.call('sum', 1, 2) after = time.time() diff = after - before print("call: {0} qps".format(Num / diff))
def doRpcClientToGoSvc(port): # print ">>>> port: ", port, " <<<<<" address = msgpackrpc.Address('localhost', port) client = msgpackrpc.Client(address, unpack_encoding='utf-8') print client.call("TestRpcInt.Echo123", ["A1", "B2", "C3"]) print client.call("TestRpcInt.EchoStruct", { "A": "Aa", "B": "Bb", "C": "Cc" })
def test_timeout(self): client = self.setup_env(); if self.__class__.ENABLE_TIMEOUT_TEST: self.assertEqual(client.call('long_exec'), 'finish!', "'long_exec' result is incorrect") client = msgpackrpc.Client(self._address, timeout=1, unpack_encoding='utf-8') self.assertRaises(error.TimeoutError, lambda: client.call('long_exec')) else: print("Skip test_timeout")
def _w2v_client(): global _word2vec_client if _word2vec_client is None: if os.environ.get('W2VSRV'): _word2vec_client = msgpackrpc.Client(msgpackrpc.Address( 'localhost', WORD2VEC_PORT), timeout=None) else: _word2vec_client = Word2VecServer() return _word2vec_client
def doRpcClientToGoSvc(port): # doCheckSocket(port) address = msgpackrpc.Address(mylocaladdr, port) client = msgpackrpc.Client(address, unpack_encoding='utf-8') print(client.call("TestRpcInt.Echo123", ["A1", "B2", "C3"])) print( client.call("TestRpcInt.EchoStruct", { "A": "Aa", "B": "Bb", "C": "Cc" }))
def run_call_async(): client = msgpackrpc.Client(msgpackrpc.Address("localhost", 18800)) before = time.time() for x in range(Num): # TODO: replace with more heavy sample future = client.call_async('sum', 1, 2) future.get() after = time.time() diff = after - before print("async: {0} qps".format(Num / diff))
def __init__(self, host, port, name, timeout=10): check_types(host, string_types) check_types(port, int_types) check_types(name, string_types) check_types(timeout, int_types) address = msgpackrpc.Address(host, port) self.client = msgpackrpc.Client(address, timeout=timeout, pack_encoding='utf-8', unpack_encoding=None) self.jubatus_client = Client(self.client, name)
def get_cluster_members(self, cluster): log.debug('requesting Jubatus cluster members for cluster %s', cluster.name) cli = msgpackrpc.Client(msgpackrpc.Address(self.node.get_host(), self.port)) try: members = list(map(lambda x: x.decode(), cli.call('get_status', cluster.name).keys())) except msgpackrpc.error.RPCError as e: if e.args[0] != 'no server found: ' + cluster.name: raise members = [] cli.close() log.debug('got Jubatus cluster members for cluster %s: %d', cluster.name, len(members)) return members
def callBack(paramNum, params): client = msgpackrpc.Client(msgpackrpc.Address("localhost", 8080)) if (paramNum == 9): result = client.call(methods[paramNum]) if (paramNum == 0): result = client.call(methods[paramNum], params[0], params[1], params[2]) elif (paramNum >= 1 and paramNum <= 4): result = client.call(methods[paramNum], params[0], params[1]) elif (paramNum >= 5 and paramNum <= 8): result = client.call(methods[paramNum], params[0]) return result
def call(): client = msgpackrpc.Client(msgpackrpc.Address("localhost", 6000)) start = time.time() if sys.version_info < (3, ): range = xrange else: import builtins range = builtins.range [client.call('sum', 1, 2) for _ in range(NUM_CALLS)] print('call: %d qps' % (NUM_CALLS / (time.time() - start)))
def setup_env(self): def _start_server(server): server.start() server.close() self._server = msgpackrpc.Server(TestMessagePackRPC.TestServer()) self._server.listen(self._address) self._thread = threading.Thread(target=_start_server, args=(self._server,)) self._thread.start() self._client = msgpackrpc.Client(self._address, unpack_encoding='utf-8') return self._client;
def check_server(port): # For Python clients, we need to generate instance for each iteration. cli = msgpackrpc.Client(msgpackrpc.Address("127.0.0.1", port)) try: cli.call("dummy") raise Exception("dummy rpc succeeded") except RPCError as e: if e.args[0] == 1: # "no such method" cli.close() return True # ... means server is fully up cli.close() return False
def __api_login(self, endpoint): self.__api_client = msgpackrpc.Client(msgpackrpc.Address( endpoint[0], endpoint[1]), unpack_encoding='utf-8') req = self.__api_client.call_async('stampery.3.auth', self.__client_id, self.__client_secret, "python-" + self.__version) req.join() self.__auth = req.result if self.__auth is None: self.__emit("error", "Couldn't authenticate") else: print("logged %s" % self.__client_id)
def test_client(): global ADDR client = msgpackrpc.Client(ADDR, unpack_encoding='utf-8') f1 = client.call('echo', 'foo') f2 = client.call('echo', 'bar') f3 = client.call('echo', 'baz') assert f2 == 'bar' assert f1 == 'foo' assert f3 == 'baz' print "EchoHandler#echo via msgpackrpc"
def __init__(self, args, simulator=None): # Static self.ML_AGENT_HOST = args['host'] self.ML_AGENT_PORT = args['port'] self.NUM_BIRDS = args['num_networks'] self.SIMULATOR = simulator self.SEND_PIXELS = args['send_pixels'] self.SCREEN_WIDTH = 400 self.SCREEN_HEIGHT = 708 self.GAP = 130 self.WALLX = 400 self.BIRD_X = 70 self.BIRD_HEIGHT = 50 self.BIRD_WIDTH = 50 self.GRAVITY = 5 self.GRAVITY_ACCELERATION = 0.2 self.JUMP_TIME = 17 self.JUMP_SPEED = 10 self.JUMP_SPEED_DECLINE = 1 self.STEPPING = args['stepping'] self.SCREEN_RESIZE_SHAPE = args['screen_resize_shape'] if 'assets' not in args: args['assets'] = 'assets' # Pygame self.screen = pygame.display.set_mode( (self.SCREEN_WIDTH, self.SCREEN_HEIGHT)) asset_path = os.path.dirname(os.path.realpath(__file__)) asset_path = os.path.join(asset_path, args['assets']) asset_background_path = os.path.join(asset_path, 'background.png') asset_1_path = os.path.join(asset_path, '1.png') asset_2_path = os.path.join(asset_path, '2.png') asset_dead_path = os.path.join(asset_path, 'dead.png') asset_bottom_path = os.path.join(asset_path, 'bottom.png') asset_top_path = os.path.join(asset_path, 'top.png') self.background = pygame.image.load(asset_background_path).convert() self.birdSprites = [ pygame.image.load(asset_1_path).convert_alpha(), pygame.image.load(asset_2_path).convert_alpha(), pygame.image.load(asset_dead_path) ] self.bottom_pipe = pygame.image.load(asset_bottom_path).convert_alpha() self.top_pipe = pygame.image.load(asset_top_path).convert_alpha() # Dynamic self.round = 0 self.reset() # If -stepping self.step = 0 # RPC proxy to machine learning agent self.client = msgpackrpc.Client( msgpackrpc.Address(self.ML_AGENT_HOST, self.ML_AGENT_PORT))
def __init__ (self, symbol=SYMBOL, resolution=60, port=PROXY_PORT): super().__init__(symbol, resolution) #self.client = RPCClient('127.0.0.1', port) self.client = msgpackrpc.Client(msgpackrpc.Address('127.0.0.1', port), unpack_encoding='utf-8') data = self.client.call('ohlcv', TICKERID, self.resolution, 256) self.data = dict( t=list(data['t']), o=list(data['o']), h=list(data['h']), l=list(data['l']), c=list(data['c']), v=list(data['v']), )
def _ping_rpc(cls, port): cli = msgpackrpc.Client(msgpackrpc.Address("127.0.0.1", port)) try: cli.call('__ping__') raise AssertionError('dummy RPC succeeded') except msgpackrpc.error.RPCError as e: if e.args[0] == 1: # "no such method" return True except: return False finally: cli.close() return False
def __init__(self, address: Tuple[str, int], timeout: float = None, reconnect_limit: int = None): self._address = address params = {} if timeout: params['timeout'] = timeout if reconnect_limit: params['reconnect_limit'] = reconnect_limit self._factory = lambda: msgpackrpc.Client(msgpackrpc.Address(*address), **params) self._using = deque() self._pool = deque()
def get_id(self): """ ID is a server identifier in form of "${IP}_${PORT}". """ if self.server_id: log.debug('reusing cached server ID = %s', self.server_id) return self.server_id log.debug('sending request: server ID') cli = msgpackrpc.Client(msgpackrpc.Address(self.node.get_host(), self.port)) server_id = cli.call('get_status', '').popitem()[0] cli.close() log.debug('got reply: server ID = %s', server_id) self.server_id = server_id return server_id
def is_ready(self): """ Pings the RPC server in one-shot. """ cli = msgpackrpc.Client(msgpackrpc.Address(self.node.get_host(), self.port)) cli._timeout = 1 try: cli.call('__dummy_method__') return True except msgpackrpc.error.RPCError as e: if e.args[0] == 1: # "no such method" return True # ... means server is fully up finally: cli.close() return False
def request_bytes(self, route, **kwargs): """ Метод выполняющий обращение msgpackrpc и возвращающий ответ """ self.logger.debug('msgpack->Request->request:\n' ' host: %s\n' ' port: %s\n' ' route: %s\n' ' arguments: %s\n', self.host, self.port, route, repr(kwargs)) # Провереяем переданный controller/action if len(route.split("/")) != 2: error_msg = "Route must be in 'controller/action' format" self.logger.error(error_msg) raise ArgumentError(error_msg) response_factory = beget_msgpack.ResponseFactory() try: client = msgpackrpc.Client(msgpackrpc.Address(self.host, self.port), timeout=self.timeout) self.logger.info('request to: %s, route: %s, args:%s', self.host, route, repr(kwargs)) answer = client.call(route, kwargs) self.logger.debug('msgpack->Request: get answer: %s', answer) response = response_factory.get_response_by_msgpack_answer(answer, encode=False) self.logger.info('result of request: %s', response.get_method_result()) # Перехватываем ошибки подключения и возвращаем информацию о проблеме. except (msgpackrpc.error.TimeoutError, msgpackrpc.error.TransportError, socket.gaierror) as e: self.logger.error('msgpack->Request: Exception: Can\'t connect: %s\n' ' %s', str(e), traceback.format_exc()) response = response_factory.get_response_by_request_error(ErrorConstructor.TYPE_ERROR_CONNECTION, str(e), ErrorConstructor.CODE_ERROR_CONNECTION) # Перехватываем все остальные ошибки except Exception as e: self.logger.error('msgpack->Request: Exception: %s\n' ' %s', str(e), traceback.format_exc()) response = response_factory.get_response_by_request_error(message=str(e)) return response
def __init__(self, length_of_simulation, ip="", port=41451, timeout_value=3600): if (ip == ""): ip = "127.0.0.1" self.client = msgpackrpc.Client(msgpackrpc.Address(ip, port), timeout=timeout_value, pack_encoding='utf-8', unpack_encoding='utf-8') #sena was here self.program_started = False #sena was here self.DRONE_INITIAL_POS = np.array([0, 0, 0]) self.default_initial_anim_time = 1 self.requiredEstimationData = [] self.isCalibratingEnergy = False self.linecount = 0 #sena was here self.online_linecount = 0 self.length_of_simulation = length_of_simulation self.is_using_airsim = True self.end = False SIZE_X = 1024 SIZE_Y = 576 focal_length = SIZE_X / 2 px = SIZE_X / 2 py = SIZE_Y / 2 flip_x_y = torch.FloatTensor([[0, 1, 0], [-1, 0, 0], [0, 0, 1]]) K_torch = torch.FloatTensor([[focal_length, 0, px], [0, focal_length, py], [0, 0, 1]]) self.intrinsics = { "f": focal_length, "size_x": SIZE_X, "size_y": SIZE_Y, "K_torch": K_torch, "flip_x_y": flip_x_y }
def __init__(self): server_rb = os.path.abspath( os.path.join(os.path.dirname(__file__), 'rb_call_server.rb')) def setpgrp(): os.setpgrp() self.proc = subprocess.Popen(['ruby', server_rb], stdout=subprocess.PIPE, preexec_fn=setpgrp) def cleanup(): RubyObject.session = None self.proc.terminate() atexit.register(cleanup) port = int(self.proc.stdout.readline()) self.proc.stdout.close() self.address = msgpackrpc.Address("localhost", port) self.client = msgpackrpc.Client(self.address, unpack_encoding='utf-8') RubyObject.session = self self.kernel = RubyObject.cast(self.client.call('get_kernel'))