def _set_cls_attr(self, cls, app_name, addr, mode, name, rpc_obj=None): attr = cls.__dict__.get(name) if rpc_obj is None: rpc_obj = grpc.get_proxy_by_addr(addr, name) else: rpc_obj._rpc_addr = addr objs = cls.app_svrs.setdefault(app_name, {}) objs[name] = rpc_obj if isinstance(attr, MultiAttr): attr._add(addr, rpc_obj) elif attr is None and mode != MultiCell.MODE: setattr(cls, name, rpc_obj) else: if isinstance(attr, grpc.RpcProxy): old_addr = attr.get_addr() else: old_addr = attr._rpc_addr if attr else None if old_addr == addr: return multi_attr = MultiAttr(name) if old_addr: multi_attr._add(old_addr, attr) multi_attr._add(addr, rpc_obj) setattr(cls, name, multi_attr)
def _new_subgame(self, app_name, sub_cmd=None, cwd=None, kw=None): """ 新建进程 """ times = 30 self.total += 1 addr = self._get_addr(app_name) if kw is None: kw = {} kw.update(dict(name=app_name, pid=os.getpid(), addr=addr)) if sub_cmd is None: sub_cmd = self.config.sub_game_cmd cmd = sub_cmd % kw if self.config.debug_key == app_name: cmd += ' subgame_debug' times = 50 if cwd is None: cwd = self.config.root_path #启动 env = None # env存在时,启动有问题 dict(subgame_index=str(self.subgame_index), ) pid = self.proc_mgr.start_process(cmd, cwd=cwd, env=env) sub_proxy = None for i in range(times): sleep(0.5) sub_proxy = grpc.get_proxy_by_addr(addr, app_name) if sub_proxy: break if sub_proxy is None: raise SystemError('new subgame error') sub_proxy._sub_pid = pid sub_proxy._sub_addr = addr return sub_proxy
def get_obj(addr_or_app, name): """ 获取远程代理对象或者本地对象 """ if hasattr(addr_or_app, 'get_proxy'): obj = addr_or_app.get_proxy(name) else: obj = get_proxy_by_addr(addr_or_app, name) return obj
def GetGRpcClient(sJsonRpcHostPort, server_id): from grpc import get_proxy_by_addr lsHP = sJsonRpcHostPort.split(':') if len(lsHP) < 2: PrintTimeMsg("sJsonRpcHostPort=(%s) error!" % sJsonRpcHostPort) return endpoint = (lsHP[0], int(lsHP[1])) return get_proxy_by_addr(endpoint, server_id)
def GetGRpcClient(sJsonRpcHostPort,server_id): from grpc import get_proxy_by_addr lsHP = sJsonRpcHostPort.split(':') if len(lsHP)<2: PrintTimeMsg("sJsonRpcHostPort=(%s) error!" % sJsonRpcHostPort) return endpoint = (lsHP[0], int(lsHP[1])) return get_proxy_by_addr(endpoint, server_id)
def rc_revengeHusongCar(self,id): yabiaoDoubleTime = Game.res_mgr.res_common.get("yabiaoDoubleTime") if not yabiaoDoubleTime: return 0, errcode.EC_NORES if str(id) not in self.player.yabiao.history: return 0, errcode.EC_REVENGEHUSONG_NOIN if self.player.yabiao.history[str(id)]["type"]!=0: return 0, errcode.EC_REVENGEHUSONG_NOTYPE res = Game.res_mgr.res_yabiao.get(self.player.yabiao.history[str(id)]["data"]["data"]["quality"]) if not res: return 0, errcode.EC_NORES from game.mgr.logicgame import LogicGame proxy = get_proxy_by_addr(self.player.yabiao.history[str(id)]["data"]["addr"], LogicGame._rpc_name_) if not proxy: return 0, errcode.EC_GETD_LOGIC_PROXY_ERR fdata = self.player.GetFightData() bhname = "" from game.mgr.guild import get_rpc_guild rpc_guild = get_rpc_guild(self.player.guild.GetGuildId()) if rpc_guild: bhname = rpc_guild.getName() historydata={"id":self.player.id,"endtime":0,"name":self.player.name,"data":{"quality":self.player.yabiao.history[str(id)]["data"]["data"]["quality"],"power":self.player.base.fa,"bhname":bhname,"sex":self.player.base.GetSex()}} resp = proxy.revengeHusongCar(self.player.id,{"id":self.player.yabiao.history[str(id)]["data"]["id"]},fdata,historydata) if not resp: return 0, errcode.EC_CALL_LOGIC_PROXY_ERR self.player.yabiao.modfiyHistoryFinish(id) respBag = {} fightResult = resp["fightLog"]["result"].get("win", 0) if fightResult: mul=1 currHour = gtime.current_hour() if currHour in yabiaoDoubleTime.arrayint1: mul=2 reward = {} for kk, vv in res.rob.items(): reward[kk]=vv*mul respBag = self.player.bag.add(reward, constant.ITEM_ADD_REVREWARD, wLog=True) dUpdate = self.player.packRespBag(respBag) dUpdate["jiebiao"] = self.player.yabiao.to_init_data() resp["allUpdate"] = dUpdate return 1, resp
def get_rpc_guild(guildId): rs = Game.rpc_guild_mgr.init_guild(guildId) if not rs: return addr = Game.rpc_guild_mgr.get_addr() proxy = get_proxy_by_addr(addr, GuildMgr._rpc_name_, DictItemProxy) proxy.dict_name = 'alls' proxy.key = guildId return proxy
def cls_get_player_proxy(cls, pid, addr=None, local=1): if addr is None: addr = Game.get_addr() if local: proxy = DictItemProxy(cls._rpc_name_, dict_name='players', key=pid, addr=addr) else: proxy = get_proxy_by_addr(addr, cls._rpc_name_, DictItemProxy) proxy.dict_name = 'players' proxy.key = pid return proxy
def init(self, listen_port=None): if listen_port is None: listen_port = self.application.config.base_port self.listen_port = listen_port self.rpc_svr = grpc.RpcServer() self.rpc_svr.bind(('0.0.0.0', listen_port)) self.rpc_svr.register(self) self.rpc_svr.start() self.main_proxy = grpc.get_proxy_by_addr( self.application.config.main_addr, MainFrame._rpc_name_) addr = (self.application.config.local_ip, self.listen_port) self.main_proxy.add_part_proxy(addr)
def cls_get_player_proxy(cls, pid, addr=None, local=1): if addr is None: addr = Game.app.get_addr() if local: proxy = DictItemProxy(cls._rpc_name_, dict_name='alls', key=pid, addr=addr) else: proxy = get_proxy_by_addr(addr, cls._rpc_name_, DictItemProxy) proxy.dict_name = 'alls' proxy.key = pid return proxy
def get_rpc_daylyPVP(force=0): if 3==int(config.serverNo[0:2]) and not hasattr(config, "p3cross"): print('test common daylyPVP') return Game.rpc_dayly_pvp_mgr_common if force: if hasattr(config, "day_addr"): return get_proxy_by_addr(config.day_addr, DaylyPVPMgr._rpc_name_) else: return Game.rpc_dayly_pvp_mgr_common days = Game.rpc_server_info.GetOpenDay() ares = Game.res_mgr.res_activity.get(constant.ACTIVITY_DAYLY_PVP) startD = ares.openDayRange[0] if startD <= days: if hasattr(config, "day_addr"): return get_proxy_by_addr(config.day_addr, DaylyPVPMgr._rpc_name_) else: return Game.rpc_dayly_pvp_mgr_common return Game.rpc_dayly_pvp_mgr_common
def add_sub_proxy(self, addr, mode, app_name, names): """ 子进程功能注册 """ addr = tuple(addr) sub_proxy = grpc.get_proxy_by_addr(addr, app_name) sub_proxy.sub_close(self._on_close) sub_proxy._app_name = app_name sub_proxy._app_names = names sub_proxy._mode = mode #通知更新 self.application.add_addr_names(app_name, addr, mode, names) for other_sub_proxy in self.sub_proxys.values(): spawn(other_sub_proxy.add_other_proxy, app_name, addr, mode, names) old_addr_names = self.get_addr_names() self.sub_proxys[tuple(addr)] = sub_proxy return old_addr_names
def logon(self, name, key): """ 登录请求 """ proxy = None try: addr = (self.local_host, self.port_for_ctrl) proxy = grpc.get_proxy_by_addr(addr, 'chat') if proxy is None: return False rs = proxy.logon(name, key) return bool(rs) except socket.error: log.info(u'登录聊天服务器失败:%s:%s', self.local_host, self.port_for_ctrl) return False finally: pass
def logon(self, name, key): """ 登录请求 """ proxy = None try: addr = (self.local_host, self.port_for_ctrl) proxy = grpc.get_proxy_by_addr(addr, 'chat') if proxy is None: return False rs = proxy.logon(name, key) return bool(rs) except socket.error: log.info(u'登录聊天服务器失败:%s:%s', self.local_host, self.port_for_ctrl) return False finally: pass
def main(): client = Client() server = get_proxy_by_addr(endpoint, server_id) print server.test_name() print server.test_params(1, 2, 3, a=1, b=2, d='*' * 1024 * 10) try: server.test_except() except ValueError as e: print e master = server.test_proxy_pickle() item5 = master['item5'] print item5.test_name() print server.test_proxy(client, _proxy=True) sleep(0.5) rpc = get_rpc_by_addr(endpoint) rpc.stop()
def grpc_get_proxy(serverid): """ 获取服务器端gprc """ from luffy.define import LOCAL_HOST_IP from luffy.models import Servers from grpc import get_proxy_by_addr GRPC_PORT = '8001' GRPC_CLIENT = 'rpc_client' log.info('grpc_get_proxy(%s)', serverid) mongo_host = Servers.query.get(serverid) if mongo_host: gport = mongo_host.gport else: ip = LOCAL_HOST_IP gport = ':'.join([LOCAL_HOST_IP, GRPC_PORT]) # gport = '127.0.0.1:8001' log.info('grpc_get_proxy:gport:%s', gport) grpc_server = GRPC_CLIENT gport = gport.split(':') addr = (gport[0], int(gport[1])) return get_proxy_by_addr(addr, grpc_server)
def grpc_get_proxy(serverid): """ 获取服务器端gprc """ from luffy.define import LOCAL_HOST_IP from luffy.models import Servers from grpc import get_proxy_by_addr GRPC_PORT = '8001' GRPC_CLIENT = 'rpc_client' log.info('grpc_get_proxy(%s)', serverid) mongo_host = Servers.query.get(serverid) if mongo_host: gport = mongo_host.gport else: ip = LOCAL_HOST_IP gport = ':'.join([LOCAL_HOST_IP, GRPC_PORT]) # gport = '127.0.0.1:8001' log.info('grpc_get_proxy:gport:%s', gport) grpc_server = GRPC_CLIENT gport = gport.split(':') addr = (gport[0], int(gport[1])) return get_proxy_by_addr(addr, grpc_server)
def _new_subgame(self, key, sub_cmd=None): """ 新建进程 """ if self.is_single: try: return self._local_app except AttributeError: self._local_app = LocalApp() self.apps[self._local_app] = [ os.getpid(), key, self._local_app.get_addr(), [] ] return self._local_app times = 30 self.subgame_index += 1 addr = self._get_addr(key) kw = dict(name=key, pid=os.getpid(), addr=addr) if sub_cmd: go_path = os.path.join(config.root_path, 'go', 'main') kw.update({"path": go_path}) if sub_cmd is None: sub_cmd = sub_game_cmd cmd = sub_cmd % kw if os.SUBGAME_DEBUG == key: cmd += ' subgame_debug' times = 10 env = None #env存在时,启动有问题 dict(subgame_index=str(self.subgame_index), ) pid = self.proc_mgr.start_process(cmd, env=env) app = None for i in xrange(times): sleep(0.5) app = get_proxy_by_addr(addr, 'app') if app: break if app is None: raise SystemError('new subgame error') app.sub_close(self._on_close) app.init(self, module_to_dict(config), _proxy=True) self.apps[app] = [pid, key, addr, []] self.names[key] = app return app, pid
def _terminate_daemon_process(self): """ Terminate the daemon process specified in the current PID file. """ if 1: DaemonRunner._terminate_daemon_process(self) else: #用app.stop import config from grpc import get_proxy_by_addr, uninit app = get_proxy_by_addr(config.admin_addr, 'app') app.stop(_no_result=True) sleep(0.5) del app uninit() timeout = 60 while timeout > 0: timeout -= 1 time.sleep(1) if not self.pidfile.is_locked(): break if timeout <= 0: sys.exit('stop error:Timeout')
def _terminate_daemon_process(self): """ Terminate the daemon process specified in the current PID file. """ if 1: DaemonRunner._terminate_daemon_process(self) else: #用app.stop import config from grpc import get_proxy_by_addr, uninit app = get_proxy_by_addr(config.admin_addr, 'app') app.stop(_no_result=True) sleep(0.5) del app uninit() timeout = 60 while timeout > 0: timeout -= 1 time.sleep(1) if not self.pidfile.is_locked(): break if timeout <= 0: sys.exit('stop error:Timeout')
def _new_subgame(self, key, sub_cmd=None): """ 新建进程 """ if self.is_single: try: return self._local_app except AttributeError: self._local_app = LocalApp() self.apps[self._local_app] = [os.getpid(), key, self._local_app.get_addr(), []] return self._local_app times = 30 self.subgame_index += 1 addr = self._get_addr(key) kw = dict(name=key, pid=os.getpid(), addr=addr) if sub_cmd: go_path = os.path.join(config.root_path, 'go', 'main') kw.update({"path":go_path}) if sub_cmd is None: sub_cmd = sub_game_cmd cmd = sub_cmd % kw if os.SUBGAME_DEBUG == key: cmd += ' subgame_debug' times = 10 env = None#env存在时,启动有问题 dict(subgame_index=str(self.subgame_index), ) pid = self.proc_mgr.start_process(cmd, env=env) app = None for i in xrange(times): sleep(0.5) app = get_proxy_by_addr(addr, 'app') if app: break if app is None: raise SystemError('new subgame error') app.sub_close(self._on_close) app.init(self, module_to_dict(config), _proxy=True) self.apps[app] = [pid, key, addr, []] self.names[key] = app return app, pid
def add_part_proxy(self, addr): addr = tuple(addr) self.part_proxys[addr] = grpc.get_proxy_by_addr( addr, PartMainFrame._rpc_name_)
def set_main_addr(self, addr, mode): log.info('set_main_addr:%s', addr) self.main_addr = addr self.mode = mode self.main_proxy = grpc.get_proxy_by_addr(self.main_addr, MainFrame._rpc_name_)
def _add(self, addr, rpc_obj): if addr in self.addrs: return if rpc_obj is None: rpc_obj = grpc.get_proxy_by_addr(addr, self.name) self.addrs[addr] = rpc_obj
def rc_diaoyuRob(self, id, quality): diaoyuCatchNum = Game.res_mgr.res_common.get("diaoyuCatchNum") if not diaoyuCatchNum: return 0, errcode.EC_NORES diaoyuRobNum = Game.res_mgr.res_common.get("diaoyuRobNum") if not diaoyuRobNum: return 0, errcode.EC_NORES diaoyuXdayReward = Game.res_mgr.res_common.get("diaoyuXdayReward") if not diaoyuXdayReward: return 0, errcode.EC_NORES if self.player.diaoyu.getDiaoyuRob() >= diaoyuRobNum.i: return 0, errcode.EC_DIAOYU_ROB_USEUP from game.mgr.room import get_rpc_diaoyu rpc_diaoyu = get_rpc_diaoyu() if not rpc_diaoyu: return 0, errcode.EC_GETD_RPC_ROOM_FAIL rrv = rpc_diaoyu.getOneByServerNo(2, config.serverNo, id) if not rrv: return 0, errcode.EC_CALL_RPC_ROOM_FAIL data = rrv["v"] if len(data) == 0: return 0, errcode.EC_DIAOYU_NOFOUNDONE if quality not in data[0]["data"]["yulou"]: return 0, errcode.EC_DIAOYU_NOFOUNDONEFISH res = Game.res_mgr.res_diaoyu.get(quality) if not res: return 0, errcode.EC_NORES if diaoyuCatchNum.i <= data[0]["data"]["catch"]: return 0, errcode.EC_DIAOYU_ROB_LIMIT from game.mgr.logicgame import LogicGame proxy = get_proxy_by_addr(data[0]["addr"], LogicGame._rpc_name_) if not proxy: return 0, errcode.EC_GETD_LOGIC_PROXY_ERR fdata = self.player.GetFightData() historydata = { "id": self.player.id, "name": self.player.name, "quality": quality, "redhp": self.player.diaoyu.hp } resp = proxy.diaoyuRob(self.player.id, data[0], fdata, historydata) if not resp: return 0, errcode.EC_CALL_LOGIC_PROXY_ERR redhp = resp["redhp"] self.player.diaoyu.sethp(redhp) fightResult = resp["fightLog"]["result"].get("win", 0) if fightResult: self.player.diaoyu.robFishOk(quality) self.player.diaoyu.addDiaoyuRob() myhistory = { "id": data[0]["id"], "name": data[0]["name"], "quality": quality } self.player.diaoyu.addHistory(2, myhistory) iOpenDay = self.player.base.GetServerOpenDay() reward = copy.deepcopy(res.reward) if iOpenDay >= diaoyuXdayReward.i: reward = copy.deepcopy(res.reward2) respBag = self.player.bag.add(reward, constant.ITEM_ADD_DIAOYU_ROBREWARD, wLog=True) else: self.player.safe_pub(msg_define.MSG_XIANSHITUISONGLIBAO_DIAOYU_F) myhistory = { "id": data[0]["id"], "name": data[0]["name"], "quality": quality } self.player.diaoyu.addHistory(3, myhistory) respBag = {} dUpdate = self.player.packRespBag(respBag) dUpdate["diaoyu"] = self.player.diaoyu.to_init_data() resp["allUpdate"] = dUpdate return 1, resp
def rc_robHusongCar(self,id): yabiaoJiebiaoLimit = Game.res_mgr.res_common.get("yabiaoJiebiaoLimit") if not yabiaoJiebiaoLimit: return 0, errcode.EC_NORES yabiaoJiebiaoNum = Game.res_mgr.res_common.get("yabiaoJiebiaoNum") if not yabiaoJiebiaoNum: return 0, errcode.EC_NORES yabiaoDoubleTime = Game.res_mgr.res_common.get("yabiaoDoubleTime") if not yabiaoDoubleTime: return 0, errcode.EC_NORES if self.player.yabiao.getYabiaoRob()>=yabiaoJiebiaoNum.i: return 0, errcode.EC_ROBHUSONG_USEUP days = self.player.base.GetServerOpenDay() ares = Game.res_mgr.res_activity.get(constant.ACTIVITY_YABIAO) startD = ares.openDayRange[0] from game.mgr.room import get_rpc_room rpc_room = get_rpc_room(startD<=days) if not rpc_room: return 0, errcode.EC_GETD_RPC_ROOM_FAIL rrv = rpc_room.getOneByServerNo(1,config.serverNo,id) if not rrv: return 0, errcode.EC_CALL_RPC_ROOM_FAIL data = rrv["v"] if len(data)==0: return 0, errcode.EC_HUSONG_NOFOUNDONE res = Game.res_mgr.res_yabiao.get(data[0]["data"]["quality"]) if not res: return 0, errcode.EC_NORES if yabiaoJiebiaoLimit.i<=len(data[0]["data"]["becatchID"]): return 0, errcode.EC_ROBHUSONG_LIMIT if self.player.id in data[0]["data"]["becatchID"]: return 0, errcode.EC_ROBHUSONG_ALREADY from game.mgr.logicgame import LogicGame proxy = get_proxy_by_addr(data[0]["addr"], LogicGame._rpc_name_) if not proxy: return 0, errcode.EC_GETD_LOGIC_PROXY_ERR fdata = self.player.GetFightData() bhname = "" from game.mgr.guild import get_rpc_guild rpc_guild = get_rpc_guild(self.player.guild.GetGuildId()) if rpc_guild: bhname = rpc_guild.getName() import app historydata={"addr":app.addr,"id":self.player.id,"endtime":0,"name":self.player.name,"data":{"quality":0,"power":self.player.base.fa,"bhname":bhname,"sex":self.player.base.GetSex()}} resp = proxy.robHusongCar(self.player.id,data[0],fdata,historydata) if not resp: return 0, errcode.EC_CALL_LOGIC_PROXY_ERR self.player.yabiao.addYabiaoRob() respBag = {} fightResult = resp["fightLog"]["result"].get("win", 0) if fightResult: self.player.yabiao.addHistory(3,data[0]) mul=1 currHour = gtime.current_hour() if currHour in yabiaoDoubleTime.arrayint1: mul=2 reward = {} for kk, vv in res.rob.items(): reward[kk]=vv*mul respBag = self.player.bag.add(reward, constant.ITEM_ADD_ROBREWARD, wLog=True) else: self.player.yabiao.addHistory(2,data[0]) dUpdate = self.player.packRespBag(respBag) dUpdate["jiebiao"] = self.player.yabiao.to_init_data() resp["allUpdate"] = dUpdate return 1, resp