def is_hit_fate(self, onum, nnum, max, type): mgr = self.player._game.hfate_mgr if max <= onum: return False, errcode.EC_FATEHIT_MAX tCanNum = max - onum if tCanNum < nnum: nnum = tCanNum #添加进活动免费次数 活动可以减的元宝 消耗的银币 消耗的元宝 n4_add = tSubCoin2 = tCostCoin1 = tCostCoin2 = 0 free2_num = mgr.get_free_coin2_num() - self.hitFateData.n4 if free2_num > 0: n4_add += free2_num for i in xrange(nnum): onum += 1 tResFateCost = self.player._game.res_mgr.fate_cost_by_num.get(onum) tCostCoin1 += tResFateCost.coin1 tCostCoin2 += tResFateCost.coin2 + tResFateCost.coin3 if free2_num >0: tSubCoin2 += tResFateCost.coin2 + tResFateCost.coin3 free2_num -= 1 if type == HITFATE_COIN1: if not self.player.cost_coin(aCoin1=tCostCoin1, log_type=COIN_HF_COIN1): return False, errcode.EC_COST_ERR elif type == HITFATE_COIN2: #扣除该次元宝观星的元宝 tCostCoin2 -= tSubCoin2 if not self.player.cost_coin(aCoin2=tCostCoin2, log_type=COIN_HF_COIN2): return False, errcode.EC_COST_ERR #免费元宝观星次数的添加 self.hitFateData.n4 += n4_add log.info("pid:%s hit_fate sub coin2:%s", self.player.data.id, tSubCoin2) return True, (onum, nnum)
def run(self): import game game.init(self) sys.modules['app'] = self self.names = None #subgame names self.sub_mgr = subgame.SubGameMgr(self) self.sub_mgr.start() self.rpc_svr.bind(self.admin_addr) self.rpc_svr.register(self) self.rpc_svr.start() self._init_web() self.web_svr.start() log.info('app started') while 1: try: self._waiter.wait() break except KeyboardInterrupt: log.info('app stoped:KeyboardInterrupt') except SystemExit: log.info('app stoped:SystemExit') except: log.log_except() break log.info('spawn app stop') spawn(self.stop) sleep(0.2) cmd = ' '.join(map(str, [sys.executable,] + sys.argv)) log.info('*****app(%s) stoped', cmd) self.stop() #守护进程方式,重启服务 if self.restarted and hasattr(self, 'daemon_runner'): self.daemon_runner.domain_restart()
def pay(cls, receipt, product_id, apple_urls=None): """ 去apple官网检查支付情况 """ if apple_urls is None: d = base64.decodestring(receipt) apple_urls = get_urls(d.find('"Sandbox"') != -1) host, port, url = apple_urls log.info('[AppStore]Pay check:%s, %s', apple_urls, product_id) jsonStr = json.dumps({"receipt-data": receipt}) headers = {"Content-type": "application/json"} data = http_post_ex(host, port, url, data=jsonStr, headers=headers, timeout=60, ssl=True) if not data: return False, None, None decodedJson = json.loads(data) status = decodedJson[u'status'] if status != 0: return False, None, decodedJson receipt = decodedJson['receipt'] #检查产品id if receipt['product_id'] != product_id: return False, None, decodedJson #检查订单号 torder = receipt['transaction_id'] return True, torder, decodedJson
def auto(self, mgr, player): """ 自动挂机, 返回:wasteTimes """ if self.data.auto: return False, errcode.EC_DEEP_NO_AUTO if self.data.fl >= FLOOR_BOSS_START - 1: return False, errcode.EC_DEEP_BOSS_NO_AUTO if self.is_auto: log.info("pid %s, is_auto :%s", player.data.id, self.is_auto) return False, errcode.EC_VALUE #从当前层开始挂机,不理会返回上层的问题 c_floor = self.auto_floors() #TODO: 测试用,60秒完成 #waste_times = 60 waste_times = c_floor * mgr.auto_times(player) #waste_times = c_floor * mgr.times_per_floor(player) auto_time = int(time.time() + waste_times) if common.is_pass_day_time(auto_time):#挂机结束时间超过今天 return False, errcode.EC_DEEP_OVER_DAY #扣费 coin = int(c_floor * mgr.auto_cost) if not player.cost_coin(aCoin2=coin, log_type=COIN_DEEP_AUTO): return False, errcode.EC_COST_ERR self.data.at = auto_time self._auto_task = spawn_later(waste_times + 5, self.auto_complete, mgr, player) self.data.auto = 1 self.modified = True return True, waste_times
def stop(self): log.info(u'主进程stop,关闭逻辑进程') for logic_app, (pid, game) in self.logics.items(): try: self._remove_logic(logic_app) except: log.log_except()
def init(self): unions = get_union_mgr_funcs().items() #unions.sort() names = [] apps = [] for name, funcs in unions: self.names[name] = funcs app = self._new_union(name, funcs) self.mgr.reg_app_addr(name, app.get_addr()) apps.append(app) names.append(name) self.union_names = names # start golang if 0: self.start_go() #init_subgames log.info('begin init_subgames:%s', names) for app in apps: self.mgr.init_subgame(app) LogicGame.init_subgame(self.mgr.app, self.mgr.app, self.mgr.get_union_infos()) self.mgr.app.pub(MSG_START) #将rpc_client注册 LogicGame.rpc_client._rpc_name_ = 'rpc_client' self.mgr.app.rpc_svr.register(LogicGame.rpc_client)
def send_msg_by_token(self, uid, token, msg, **kw): if self.apns_started: try: log.info("identifier:%s,uid:%s,token:%s", kw['identifier'], uid, token) self.send_apns_msg(token, msg, **kw) except Exception, e: log.log_except()
def start(self): self.stoped = False self.svr = grpc.RpcServer() self.svr.bind(self.addr) self.svr.register(self) self.svr.start() # 用来阻塞住主协程 self._waiter = gevent.event.Event() self._waiter_stoped = gevent.event.Event() try: while 1: #检查父进程是否已经关闭 if not self._exist_pid(): self._wait_game_stop() log.warn(u'主进程(%s)已经退出,子进程(%s)将自动关闭', self.pid, os.getpid()) os.environ['PARENT_STOPED'] = '1' break try: if self._waiter.wait(2): break except KeyboardInterrupt: pass except Exception as e: log.info('subgame app error:%s', e) try: self._stop() finally: self._waiter_stoped.set() sleep(2) self._svr_stop() sleep(0.5)
def del_expire_mail(self): """ 每日凌晨4点删除过期的邮件 """ four = cur_day_hour_time(4) ct = current_time() sleep_time = four-ct if ct<four else MailMgr.SLEEP_TIME-(ct-four) log.info("del_expire_mail sleep %s times", sleep_time) sleep(sleep_time) store = Game.rpc_store while 1: #计算段数 limit = MailMgr.LIMIT a_n = store.count(Mail.TABLE_NAME, {'_id':{FOP_NE:0}}) u_n = a_n/limit+1 if a_n%limit else a_n/limit sections = [i for i in xrange(u_n)] sections.append(u_n) sections.sort(reverse=True) ct = current_time() onls = Game.rpc_player_mgr.get_online_ids() del_time = ct - MailMgr.EXPIRE_TIME querys = {'pid':{FOP_NIN:onls}, 'ct':{FOP_LTE:del_time}} for section in sections: mails = store.query_loads(Mail.TABLE_NAME, querys=querys, limit=limit, skip=section*limit) for m_d in mails: self._del_mail(m_d, store) sleep(MailMgr.SLEEP_TIME)
def _svr_stop(self): if not self._exist_pid(): self.svr.close() else: self.svr.stop() grpc.uninit() log.info('grpc.uninit(%s)', self.name)
def kill_out_apply(self): """ 处理申请过期的申请者 """ cur_time = common.current_time() u_d = self.pid2applyjson.copy() for pid, js in u_d.iteritems(): if cur_time - js[TIME] >= ONE_DAY_TIME: self.del_apply_by_pid(pid) log.info("player :%s apply is out time was killed", pid)
def close(self): if self.rpc: log.info('client stop!') self.rpc.stop() self.rpc = None exc = ValueError('client stop') for w in self.waits.itervalues(): w.set_exception(exc)
def GET(self): data = web.input() data.ip = web.ctx.ip log.info('[dpay]callback:%s', data) act_cls = ACTS[CB_ACT_PAY] code, desc = act_cls.GET(sdk, data) log.info('[dpay]callbacked:%s', (code, desc)) return make_result(code, desc)
def modify_sys_argv(): log.info("Gunicorn Transform!") import sys, os global origin_sys_argv origin_sys_argv = sys.argv os.chdir(config.app_path) bind_address = '%s:%s' % addr sys.argv = ['gunicorn', '-b', bind_address, '-k', 'gevent_pywsgi', '-w', '2', 'main:app']
def _get_addr(self, key): if key in self.key_addrs: return self.key_addrs[key] if self.free_addrs is not None: return self.free_addrs.pop(0) #linux系统下,使用unix socket addr = os.path.join(config.cfg_path, '%s.sock' % key) log.info('sub_game addr: %s', addr) return addr
def POST(self): d = web.data() data = json.loads(d) data['ip'] = web.ctx.ip log.info('[UC]callback:%s', str(data)) act_cls = ACTS[CB_ACT_PAY] code, desc = act_cls.GET(sdk, data) log.info('[UC]callbacked:%s', (code, desc)) return make_result(code, desc)
def player_own(self, pid, ally = None): """ 得到玩家自己的同盟信息 """ r_dict = ally.own(pid) i = self.allys_rank.index(ally.data.id) + 1 r_dict['rank'] = i d = ally.data num = ally.member_num log.info("aid:%s rank: %s, lv:%s, member_num:%s, exp:%s", d.id, i, d.level, num, d.exp) return True, r_dict
def start(self): store = Game.rpc_res_store apns = store.get_config(NOTIFY_APNS, None) if apns is not None: if isinstance(apns, (str, unicode)): apns = eval(apns) sanbox, pem = apns self.start_apns(pem, config.cfg_path, sanbox) log.info('*****[notify]APNS service start!')
def stop(self): if not self.started: return self.started = False log.info("wait for store:%s", self.store.db_name) self.pool_get.join() self.pool_set.join() log.info("end wait for store") self._check_task.kill() self._set_task.kill()
def _free_logic(self, count): """ 检查是否有空余的逻辑进程,释放 """ for app in self.logics.keys(): if count <= 0 or len(self.logics) <= config.logic_pool: return game = app.get_proxy('game') if game.get_count() == 0: log.info(u'释放空闲的逻辑进程') self._remove_logic(app) count -= 1
def main(): #assert len(sys.argv) == 3 log.info('[subgame] start:%s', sys.argv) app_name = sys.argv[-3] pid = int(sys.argv[-2]) addr = sys.argv[-1] if '(' in sys.argv[-1]: addr = eval(addr) app = Application(app_name, pid, addr) app.start()
def first_charge(self, bag_item): """发送首冲奖励""" rw_mail = Game.res_mgr.reward_mails.get(RW_MAIL_FIRST_CHARGE) content = RW_MAIL_FIRST_CHARGE pid = self.player.data.id log.info("first_charge mailType:%s, pid:%s, items:%s", content, pid, bag_item) if not bag_item: return Game.mail_mgr.send_mails(pid, MAIL_REWARD, rw_mail.title, content, bag_item, param=rw_mail.content)
def POST(self): data = web.input() data.ip = web.ctx.ip log.info('[idsc]ChenckPay:%s', data) act_cls = ACTS[CB_ACT_PAY] code, desc = act_cls.ChenckPay(sdk, data) log.info('[idsc]finish ChenckPay:%s', (code, desc)) if code == CODE_SUCC: return json.dumps({'err_code':0, 'desc':desc}) else: return json.dumps({'err_code':1, 'desc':desc})
def player_pay_back(self, pid, rid, coin): p = self.get_rpc_player(pid) if p: rs, lv = p.pay_back(rid, self.first_reward, coin) log.info('online pay_back(%s, %s):%s, %s', pid, rid, rs, lv) else:#离线状态 g = Game.one_game() rs, lv = g.sync_exec(handle_pay_back, (pid, rid, self.first_reward, coin), _pickle=True) log.info('offline pay_back(%s, %s):%s, %s', pid, rid, rs, lv) return rs, lv
def _stop(self): if self.stoped: return self.stoped = True log.info('subgame app(%s) stoped:%s', self.name, self.names.keys()) for obj in self.names.values(): if hasattr(obj, 'stop'): try: obj.stop() except: log.log_except('stop(%s) error', obj)
def _log_info(self, pass_time): if self.quese_set.qsize() != 0 or self.set_step_count != 0 or \ self.get_step_count > 100: #空闲时候也会读数据 p = self.set_step_count / float(pass_time) p_get = self.get_step_count / float(pass_time) log.info("[StorePool-%s]set:::size:%d, total:%d, %d, %.2f c/s:::, get:::size:%d, total:%d, %d, %.2f", self.store.db_name, self.pool_set.size, self.set_count, self.set_step_count, p, self.pool_get.size, self.get_count, self.get_step_count, p_get) self.set_step_count = 0 self.get_step_count = 0
def _init_web(self): from gevent import pywsgi from corelib import Http10WSGIHandler import webapp web_addr = config.web_addr self.wsgi_app = webapp.get_wsgi_app() self.web_svr = pywsgi.WSGIServer(web_addr, self.wsgi_app, log=log if config.debug else None, handler_class=Http10WSGIHandler) self.web_svr.reuse_addr = 1 log.info('game web:%s', web_addr)
def _init_vip_level(self): """ 根据累计重置元宝数,确定vip等级 只升级,不降级,方便实现送vip等级等人为调整功能 """ lv = self.player._game.vip_mgr.get_vip_level(self.player.data.vipCoin) if lv > self.player.data.vip: self.player.log_normal(PL_VIP_UPGRADE, lv=lv) log.info('player(%s)vip level up:%s', self.player.data.name, lv) self._send_reward(int(lv)) self.vip = lv self.player.pub_vip_level()
def _get_addr(self, app_name): """ 根据app_name,获取子进程用的addr """ if app_name in self.addrs: addr = self.addrs[app_name] elif self.config.free_addrs: addr = self.config.free_addrs.pop(0) elif self.unix_path: # linux系统下,使用unix socket addr = os.path.join(self.unix_path, '%s.sock' % app_name) else: raise ValueError('no free addr for app_name(%s)' % app_name) log.info('sub_game addr: %s', addr) return addr
def add(self, mid, pid, name, rid, uid): """ 玩家登陆,防止在短时间内重复登录 """ self._add_name_id(pid, name, rid) if self.logons.get(pid): log.info(u'禁止玩家(%s-%s)短时登录', pid, name) return False self.logons.set(pid, 1) self._users[uid] = mid, pid self._players[pid] = mid self._sub_mgrs[mid][1].add(pid) self.safe_pub(MSG_LOGON, pid) return True
def is_debug_time(self): """ 测试期间只允许特定IP登陆 """ if not self._debug_status or not self._debug_ips: return True rpc = client_rpc.get_cur_rpc() ip = rpc.addr[0] if ip in self._debug_ips: return True log.info('during debug time in_ip:%s forbid :%s', self._debug_ips, ip) return False
def _log_info(self, pass_time): if self.quese_set.qsize() != 0 or self.set_step_count != 0 or \ self.get_step_count > 100: #空闲时候也会读数据 p = self.set_step_count / float(pass_time) p_get = self.get_step_count / float(pass_time) log.info( "[StorePool-%s]set:::size:%d, total:%d, %d, %.2f c/s:::, get:::size:%d, total:%d, %d, %.2f", self.store.db_name, self.pool_set.size, self.set_count, self.set_step_count, p, self.pool_get.size, self.get_count, self.get_step_count, p_get) self.set_step_count = 0 self.get_step_count = 0
def domain_restart(self): """ 重启守护进程 """ import os config = sys.modules['config'] argv = os.environ['APP_ARGV'] self.pidfile.break_lock() restart_path = os.path.join(config.root_path, 'restart.py') if not os.path.exists(restart_path): restart_path = os.path.join(config.root_path, 'restart.pyc') args = '%s %s' % (sys.executable, argv) log.info('重启服务:%s', args) os.system('python %s %s' % (restart_path, args))
def cron_clean_data_zero(self, inited=False): """ 定在每天凌晨0点初始化的处理 """ now = datetime.datetime.now() refresh_time = custom_today(hour=0, minute=0) refresh_time += ONE_DAY_DELTA sleep_times = (refresh_time - now).seconds + 5 self.timer_set.call_later(sleep_times, self.cron_clean_data_zero) #执行游戏逻辑刷新 if not inited: log.info(u"每日0点定时刷新开始") spawn(self.on_cron_clean_data_zero)
def init_app(): global inited if inited: return inited = 1 #游戏功能子进程,自己初始化sns Game.init_snss() from webapi import snss, SNS_UC #uc接口 if SNS_UC in snss: uc = snss[SNS_UC] uc.cb_init(app, game_url, callback=0) log.info('app mapping:\n%s', '\n'.join(map(str, app.mapping)))
def clear_ally(self, name): """GM命令删除除帮主已外的成员""" from game.base.constant import ALLY_MAIN if not self.set_gm_ally_by_name(name): return 0 pids = [] for assist_obj in self.gm_ally.assist_objs.values(): if assist_obj.data.duty != ALLY_MAIN: pids.append(assist_obj.data.pid) for pid in pids: self.gm_ally._kick_out("test_gm", pid) log.info("+++del player ok pid: %s++", pid) return 1
def start(self): self.init_frame() self.frame.start() while 1: try: self._waiter.wait() break except KeyboardInterrupt: log.info('app stoped:KeyboardInterrupt') except SystemExit: log.info('app stoped:SystemExit') except: log.log_except() break log.info('spawn app stop') spawn(self.stop) sleep(0.2) cmd = ' '.join(list(map(str, [sys.executable,] + sys.argv))) log.info('*****app(%s) stoped', cmd) self.stop() #守护进程方式,重启服务 if self.restarted and hasattr(self, 'daemon_runner'): self.daemon_runner.domain_restart()
def _auto_start(self): global arena_auto_start, arena_level sleep_times = 60 * 5 log.info('arena auto_start(%s) running', arena_auto_start) while 1: sleep(sleep_times) c = PlayerData.count({FN_PLAYER_LEVEL: {FOP_GTE: arena_level}}) if c >= arena_auto_start: log.info('arena auto start:%d', c) self.init() self.is_start = True self.start() self._auto_start_task = None return
def get_near_online(self, player): rpc_player_mgr = player._game.rpc_player_mgr onl_ids = player._game.rpc_scene_mgr.get_online_ids( random_num=NUM_PER_PAGE) rl = [] for onl_id in onl_ids: if onl_id == player.data.id: continue rpc_player = rpc_player_mgr.get_rpc_player(onl_id) try: social_info = rpc_player.social_online_info() rl.append(social_info) except: log.info("pid:(%s) is login out", onl_id) return True, dict(rl=rl)
def main(): #assert len(sys.argv) == 3 log.info('[subgame] main:%s', sys.argv) app_name = sys.argv[-3] pid = int(sys.argv[-2]) addr = sys.argv[-1] if isinstance(addr, str): addr = eval(addr) addr = tuple(addr) app = Application(app_name, pid, addr) try: app.start() except: log.log_except()
def start(self): NOTIFY_APNS = 'notify_apns' _coll_config = MongoFive(g.GAMEBASE, EXT.COLL_GCONFIG, host=g.mongo_host) shows = {'value': 1} t_apns = _coll_config.filter({"key": NOTIFY_APNS}, shows) if t_apns is not None: t_apns = t_apns[0]['value'] if isinstance(t_apns, (str, unicode)): t_apns = eval(t_apns) sanbox, pem = t_apns import config self.start_apns(pem, config.cfg_path, sanbox) log.info('*****[notify]APNS service start!')
def stop(self): if self.stoped: return self.stoped = True log.info('[subFrame](%s) stop', self.name) for name in self.names: obj = self.rpc_svr.get_export(name) if hasattr(obj, 'stop'): try: obj.stop() except: log.log_except('stop(%s) error', obj) #---------------------- self.rpc_svr.stop() grpc.uninit()
def _pay_back(self, pay_data): """ 支付成功回调 """ pay = Pay(adict=pay_data) goods = self.reward_goods.get(pay.rid, None) pay.coin = goods.coin if goods else 0 #首充翻倍要用到coin log.info('pay_back(%s)', pay_data) rs, lv = self.player_pay_back(pay.pid, pay.rid, pay.coin) if not rs: return log.info('pay_back(%s) done', pay.porder) pay.dt = current_time() pay.lv = lv pay.save(self.pay_store) self.safe_pub(MSG_VIP_PAY, pay.pid, pay.rid, pay.coin)
def _init_web(self): from gevent import pywsgi from corelib.geventfix import Http10WSGIHandler from game.gm import webapp web_addr = ('0.0.0.0', config.web_addr[1]) self.wsgi_app = webapp.get_wsgi_app() self.web_svr = pywsgi.WSGIServer(web_addr, self.wsgi_app, log=log if config.debug else None, environ=os.environ, handler_class=Http10WSGIHandler) self.web_svr.reuse_addr = 1 self.web_svr.environ['SERVER_NAME'] = 'game' log.info('game web:%s', web_addr)
def POST(self): data = web.input() data.ip = web.ctx.ip log.info('[idsc]callback:%s', data) act_cls = ACTS[CB_ACT_PAY] try: code, desc = act_cls.GET(sdk, data) except: log.log_except() return json.dumps({'success': 0, 'desc': 'sys error'}) log.info('[idsc]callbacked:%s', (code, desc)) if code == CODE_SUCC: return json.dumps({'success': 1, 'desc': desc}) else: return json.dumps({'success': 0, 'desc': desc})
def _loop(self): """ 定时检查购买支付情况 """ log.info('vip_pay_back start') querys = dict(sid=self.sid, dt=0, status=1, torder={FOP_NE:''}) while 1: sleep(5) try: pays = self.pay_store.query_loads(Pay.TABLE_NAME, querys) for pay in pays: try: self._pay_back(pay) except: log.log_except() except: log.log_except()
def start(self): if not self.stoped: return log.info('[subFrame] start:%s', self.addr) self.stoped = False #去主进程注册输出的对象 names = list(self.names.keys()) self.application.add_my_names(self.name, self.addr, self.mode, [(name, obj) for name, obj in self.names.items()]) addr_names = self.main_proxy.add_sub_proxy(self.addr, self.mode, self.name, names) for app_name, addr, mode, names in addr_names: self.add_other_proxy(app_name, addr, mode, names) self.application.after_start()
def new_logic(self): """ 新建游戏逻辑进程 """ log.info(u'新建游戏逻辑进程') mgr = self.mgr app, pid = mgr._new_subgame(self._get_key()) name = mgr._app_register(app, new_logic_game)[0] game = app.get_proxy(name) self.mgr.init_subgame(app) game.init() game.start() self.logics[app] = pid, game #注册 Game.reg_other_game(game, pid) log.debug('new_logic:%s, %s', pid, game) app.sub_close(self._on_close) spawn_later(1, self.mgr._new_game, app, game, pid) return app
def get_server_id(self): """ 服id """ if not self.server_id: #server id host, port = config.inet_ip, config.player_addr[1] try: servers = Game.rpc_res_store.query_loads( TN_SERVER, dict(host=host, port=port)) if len(servers) != 1: log.error(u'server id error:%s', str(servers)) raise ValueError('server id error') self.server_id = servers[0]['sid'] log.info('server_id:%s', self.server_id) except: if not self.server_id: raise return self.server_id
def contribute(self, pid, name, train, ally = None): main_data = ally.data ally_levels = self.res_mgr.ally_levels #配成从0开始所以判断下一级需要加1 level_obj = ally_levels.get(main_data.level + 1) if level_obj: up_exp = level_obj.exp main_data.exp += train if main_data.exp >= up_exp and main_data.level < len(ally_levels): ally.level_up() self.safe_pub(MSG_ALLY_UP, main_data.id, main_data.level) log.info("contribute ally_id:%s,cur_exp:%s,lev_up_exp:%s", main_data.id, main_data.exp, up_exp) main_data.exp -= up_exp ally.contribute(pid, name, train) return True, None else: log.error('contribute in ally.py level:%s', ally.data.level) return False, None
def send_msgs(self, str_pids, msg, is_all=False, **kw): """ 向某玩家推送消息 """ if isinstance(msg, unicode): msg = msg.encode('utf-8') tokens = self.get_tokens(is_all, str_pids) if not tokens: return 0, u"数据得到空请确定pid正确或者数据库不为空" from datetime import datetime _start = datetime.now().strftime('%Y-%m-%d %H:%M:%S') log.info("%s token_send_start,msg:%s", _start, msg) kw['identifier'] = 0 for token, uid in tokens.iteritems(): if not token: continue kw['identifier'] += 1 self.send_msg_by_token(uid, token, msg, **kw) _end = datetime.now().strftime('%Y-%m-%d %H:%M:%S') log.info("%s token_send_end, num:%s", _end, kw['identifier']) return 0, u'token发送完成'
def go_get(self, *args): """ 类似go get,先删除gopath/下的目录再执行go get """ from shutil import rmtree from os.path import join, exists pkgs = [ ('bitbucket.org/seewind/grpc', 'golang/grpc'), ('bitbucket.org/efun/gateway', ''), ] gopath = os.environ.get("GOPATH") #remove for root, pkg in pkgs: pkg_path = join(gopath, "src", root) log.info("remove:%s", pkg_path) if exists(pkg_path): rmtree(pkg_path) #go get cmd = "go get %s/%s" % (root, pkg) log.info("exec: %s", cmd) os.system(cmd)
def _rpc_on_close(cls, proxy): """ 功能服关闭,等待重新链接 """ name = proxy._rpc_name addr, key = proxy.get_proxy_id() if os.environ.get('PARENT_STOPED', None): return if Game.app.stoped: return log.info('reconnect rpc(%s):%s', name, addr) while 1: new = get_obj(addr, key) if new is None or not new.valid(): sleep(0.1) continue cls.add_rpc_mgr(name, new) funcs = cls.rpc_init_funcs.get(name, []) for f in funcs: spawn(f, new) break
def init(): """ web.py 设定 - 开始 """ global app, render, template_render, api_url, snss global aes_encrypt from model import logon_store from game.store.define import (GF_webUrl, GF_SDK91_APP_ID, GF_SDK91_APP_KEY, GF_SDK91_URLS, GF_DPAY_APP_ID, GF_DPAY_APP_KEY, GF_DPAY_URLS, GF_CLIENTRPC_AESKEY) web.config['debug'] = web_config.auto_reload app = web.auto_application() web.config.session_parameters['timeout'] = 60 * 10 #缓存有效时间 use_cache = web_config.use_cache loc = web_config.templates_path log.info('templates_path:%s', loc) base_layout = 'backstage/layout' session_initializer = {"login": 0, "name": None} globals_dict = { 'hasattr': hasattr, } render = web.template.Render(cache=use_cache, loc=loc) template_render = web.template.Render(cache=use_cache, loc=loc, base=base_layout, globals=globals_dict) log.debug(u'web参数:templates_path=%s, static_path=%s', loc, web_config.static_path) api_url = logon_store.get_config(GF_webUrl) #初始化sns模块 from game import Game snss = Game.init_snss(get_config=logon_store.get_config, web_app=app, api_url=api_url, res_store=logon_store) from corelib.aes import new_aes_encrypt key = logon_store.get_config(GF_CLIENTRPC_AESKEY) aes_encrypt = new_aes_encrypt(key)
def _all_tokens(self): """ 通知所有玩家 """ dbs = Servers.query.all() db_res = g.current_server.db_res log.info("++++++the db_res is:%s", db_res) notify_dbs = [] all_db_users = [] dt_shows = {EXT.KEY_MONGO_ID: 1, EXT.KEY_DT: 1} for db in dbs: if db.db_res == db_res: _user = MongoFive(db.db_user, EXT.BASEUSER_USER, host=g.mongo_host) pages = _user.count() / num_per_page + 1 for page in xrange(pages): dt = _user.paginate(page + 1, num_per_page) all_db_users.extend(dt) return all_db_users
def _msg_app_del(self, app_name, addr, names): """ 子进程退出,清理数据 """ if SubPlayerMgr._rpc_name_ not in names: return log.info('[player_mgr]unreg sub_player_mgr:%s', app_name) self.app_pids.pop(app_name, None) #缓存清理,玩家退出 def _unreg(): pids = [ pid for pid, _app_name in self._logouts.items() if _app_name == app_name ] for pid in pids: self._logouts.pop(pid, None) for pid, _app_name in self._players.items(): if _app_name == app_name: self.del_player(_app_name, pid, str(uuid.uuid1())) spawn(_unreg)
def rc_login1(self, user, key): """ client登陆到逻辑进程 user: user id """ if self.inited: return resp_f = 'login1' self.inited = 1 log.info(u'账号(%s)登陆', user) self.key = key self.data.id = user if not self.logon(): log.error(u'账号(%s)登陆错误', user) resp = pack_msg(resp_f, 0, err=errcode.EC_LOGIN_ERR) else: #resp.server_time = int(time.time()) resp = pack_msg(resp_f, 1) self.inited = 2 spawn_later(1, self._init_waiter.set) return resp
def refurbish(self): """ 10分钟刷新一次同盟排名 """ def sort_rank(ally_id): if ally_id not in self.allys: return 0, 0, 0 ally = self.allys[ally_id] return -ally.data.level, -ally.data.exp, -ally.member_num while 1: self.allys_rank.sort(key=sort_rank) i = 0 for aid in self.allys_rank: i += 1 ally = self.allys[aid] d = ally.data num = ally.member_num aid = d.id log.info("aid:%s rank: %s, lv:%s, member_num:%s, exp:%s", aid, i, d.level, num, d.exp) if i > AllyMgr.MAX_RANK: break sleep(AllyMgr.REFURBISH_TIME)