def __registerHttpEntry(handler, method, entry): # 确定HTTP的API路径 httppath = entry.get('httppath', None) if not isinstance(httppath, (str, unicode)) or len(httppath) <= 0: httppath = method.__name__.replace('_', '/') if httppath.find('do/http/') == 0: httppath = httppath[7:] if httppath[0] != '/': httppath = '/' + httppath while httppath.find('//') >= 0: httppath = httppath.replace('//', '/') entry['httppath'] = httppath # 确定是否需要IP过滤 entry['ip_filter'] = __dummyIpFilter if entry['need_ip_filter']: ip_filter = getattr(handler, 'ip_filter', None) if callable(ip_filter): entry['ip_filter'] = ip_filter # 确定返回的ContentType if entry['response'] == 'json' or entry['jsonp'] == 1: entry['content_type'] = CONTENT_TYPE_JSON else: entry['content_type'] = CONTENT_TYPE_HTML if httppath in __http_path_methods: tylog.info('WARRING !! the http path already defined !! httppath=' + str(httppath)) __http_path_methods[httppath] = (method, entry) tylog.info('HTTP Add Entry ->', httppath, 'method=', method) return httppath
def __registerHttpEntry(handler, method, entry): # 确定HTTP的API路径 httppath = entry.get('httppath', None) if not isinstance(httppath, (str, unicode)) or len(httppath) <= 0 : httppath = method.__name__.replace('_', '/') if httppath.find('do/http/') == 0 : httppath = httppath[7:] if httppath[0] != '/' : httppath = '/' + httppath while httppath.find('//') >= 0 : httppath = httppath.replace('//', '/') entry['httppath'] = httppath # 确定是否需要IP过滤 entry['ip_filter'] = __dummyIpFilter if entry['need_ip_filter'] : ip_filter = getattr(handler, 'ip_filter', None) if callable(ip_filter) : entry['ip_filter'] = ip_filter # 确定返回的ContentType if entry['response'] == 'json' or entry['jsonp'] == 1: entry['content_type'] = CONTENT_TYPE_JSON else: entry['content_type'] = CONTENT_TYPE_HTML if httppath in __http_path_methods : tylog.info('WARRING !! the http path already defined !! httppath=' + str(httppath)) __http_path_methods[httppath] = (method, entry) tylog.info('HTTP Add Entry ->', httppath, 'method=' , method) return httppath
def addWebRoot(webroot): if not webroot in __path_webroots : webroot = os.path.abspath(webroot) + os.path.sep tylog.info('HTTP Add WEBROOT ->', webroot) __path_webroots.append(webroot) else: tylog.info('HTTP Add WEBROOT already add !!->', webroot)
def onAction(self, action, name): tylog.info('BaseActionHandler.onAction' '| action, name:', action, name) ret = None if action == 'generate': ret = self.doGenerate(name) elif action == 'show': ret = self.doShowPage(name) elif action == 'get': revision = runhttp.getParamStr("revision") branch = runhttp.getParamStr("branch") ret = self.doGet(name, branch, revision) elif action == 'svnLog': branch = runhttp.getParamStr("branch") ret = self.doSvnLog(name, branch) elif action == 'commit': branch = runhttp.getParamStr("branch") log = runhttp.getParamStr("log") ret = self.doCommit(name, branch, log) tylog.info('BaseActionHandler.onAction' '| action, name:', action, name, '| ret:', ret) return ret
def addWebRoot(webroot): if not webroot in __path_webroots: webroot = os.path.abspath(webroot) + os.path.sep tylog.info('HTTP Add WEBROOT ->', webroot) __path_webroots.append(webroot) else: tylog.info('HTTP Add WEBROOT already add !!->', webroot)
def mainloop(): tylog.info('Main loop begin.') stackless.tasklet(reactor.run)() reactor.callLater(0, stackless.schedule) stackless.run() tylog.info('Main loop over.') sys.exit(0)
def do_http_add_action(self, action_user, action_name, action_params): action = actqueue.add_action(action_name, action_params, action_user) tylog.info('do_http_add_action->', action) mo = MsgPack() mo.setCmd('add_action') mo.setResult('action', action) return mo
def handlerHttpRequest(httprequest): if InitFlg.isInitOk != 1: mo = MsgPack() mo.setError(1, 'http system not startup') mo = __stringifyResponse(0, mo) doFinish(mo, CONTENT_TYPE_HTML) return mo = None try: session = stackless.getcurrent()._fttask.session session['ishttp'] = 1 rpath = httprequest.path if TRACE_RESPONSE: tylog.info('HTTPREQUEST', rpath, httprequest.args) # 当前服务处理 funhttp, entry = __http_path_methods.get(rpath, (None, None)) if funhttp == None or entry == None: __handlerHttpStatic(httprequest) return # 查找静态资源返回 # IP 地址过滤 if entry['need_ip_filter']: ip = getClientIp() mo = entry['ip_filter'](ip) if mo: mo = __stringifyResponse(entry['jsonp'], mo) doFinish(mo, entry['content_type']) return # IP 过滤失败, 返回 # 执行动态调用 try: mo = funhttp() # 最新版本的 @http_request_entry 方法 if mo == None: mo = MsgPack() mo.setCmd(rpath) mo.setError(1, 'http api return None') except: tylog.error() mo = MsgPack() mo.setCmd(rpath) mo.setError(1, 'http api exception') mo = __stringifyResponse(entry['jsonp'], mo) doFinish(mo, entry['content_type'], rpath) except: tylog.error() mo = MsgPack() mo.setCmd(rpath) mo.setError(1, 'system exception return') mo = __stringifyResponse(0, mo) doFinish(mo, CONTENT_TYPE_HTML)
def handlerHttpRequest(httprequest): if InitFlg.isInitOk != 1: mo = MsgPack() mo.setError(1, 'http system not startup') mo = __stringifyResponse(0, mo) doFinish(mo, CONTENT_TYPE_HTML) return mo = None try: session = stackless.getcurrent()._fttask.session session['ishttp'] = 1 rpath = httprequest.path if TRACE_RESPONSE : tylog.info('HTTPREQUEST', rpath, httprequest.args) # 当前服务处理 funhttp, entry = __http_path_methods.get(rpath, (None, None)) if funhttp == None or entry == None: __handlerHttpStatic(httprequest) return # 查找静态资源返回 # IP 地址过滤 if entry['need_ip_filter'] : ip = getClientIp() mo = entry['ip_filter'](ip) if mo : mo = __stringifyResponse(entry['jsonp'], mo) doFinish(mo, entry['content_type']) return # IP 过滤失败, 返回 # 执行动态调用 try: mo = funhttp() # 最新版本的 @http_request_entry 方法 if mo == None: mo = MsgPack() mo.setCmd(rpath) mo.setError(1, 'http api return None') except: tylog.error() mo = MsgPack() mo.setCmd(rpath) mo.setError(1, 'http api exception') mo = __stringifyResponse(entry['jsonp'], mo) doFinish(mo, entry['content_type'], rpath) except: tylog.error() mo = MsgPack() mo.setCmd(rpath) mo.setError(1, 'system exception return') mo = __stringifyResponse(0, mo) doFinish(mo, CONTENT_TYPE_HTML)
def addHandler(handler): ''' 添加一个HTTP请求处理的入口实例 参数: handler HTTP请求的类或实例, 其定义的HTTP方法必须使用: @markHttpRequestEntry 进行修饰 ''' tylog.info('HTTP Add Handler ->', handler) for key in dir(handler): method = getattr(handler, key) if callable(method) : entry = getattr(method, '_http_request_entry_', None) if isinstance(entry, dict) : __registerHttpEntry(handler, method, entry)
def initialize(options_): global options options = options_ tylog.info('==== initialize begin ====') runhttp.addWebRoot(fsutils.appendPath(options.workpath, 'webroot')) runhttp.addHandler(ActionHandler(options)) runhttp.addHandler(TexasActionHandler(options)) runhttp.addHandler(T3cardActionHandler(options)) runhttp.addHandler(T3flushActionHandler(options)) runhttp.addHandler(DizhuActionHandler(options)) runhttp.addHandler(ConfigActionEntry(options)) tylog.info('==== initialize end ====')
def _checkBusy(self): if TyTasklet.concurrent_task_count >= TyTasklet.MAX_CONCURRENT: # 只在空闲向繁忙转换时,打印一次 if TyTasklet.BUSY_FLAG == 0: tylog.error("_checkBusy: too much task(%d)!" % TyTasklet.concurrent_task_count) TyTasklet.BUSY_FLAG = 1 else: # 只在繁忙向空闲转换时,打印一次 if TyTasklet.BUSY_FLAG == 1: tylog.info("_checkBusy: task count recover(%d)!" % TyTasklet.concurrent_task_count) TyTasklet.BUSY_FLAG = 0 return TyTasklet.BUSY_FLAG
def addHandler(handler): ''' 添加一个WS请求处理的入口实例 参数: handler WS请求的类或实例, 其定义的WS方法必须使用: @markWsRequestEntry 进行修饰 ''' tylog.info('WS Add Handler ->', handler) for key in dir(handler): method = getattr(handler, key) if callable(method): entry = getattr(method, '_ws_request_entry_', None) if isinstance(entry, dict): __registerWsEntry(handler, method, entry)
def addHandler(handler): ''' 添加一个HTTP请求处理的入口实例 参数: handler HTTP请求的类或实例, 其定义的HTTP方法必须使用: @markHttpRequestEntry 进行修饰 ''' tylog.info('HTTP Add Handler ->', handler) for key in dir(handler): method = getattr(handler, key) if callable(method): entry = getattr(method, '_http_request_entry_', None) if isinstance(entry, dict): __registerHttpEntry(handler, method, entry)
def addHandler(handler): ''' 添加一个WS请求处理的入口实例 参数: handler WS请求的类或实例, 其定义的WS方法必须使用: @markWsRequestEntry 进行修饰 ''' tylog.info('WS Add Handler ->', handler) for key in dir(handler): method = getattr(handler, key) if callable(method) : entry = getattr(method, '_ws_request_entry_', None) if isinstance(entry, dict) : __registerWsEntry(handler, method, entry)
def startup(options): logfile = getattr(options, 'logfile', None) if logfile: tylog.info('Open Log File :', logfile) log_path = fsutils.getParentDir(logfile) log_file = fsutils.getLastPathName(logfile) tylog.initLog(log_file, log_path) port = getattr(options, 'httpport', 0) if port > 0: listenHttp(port) port = getattr(options, 'wsport', 0) if port > 0: listenWs(port) initfunc = getattr(options, 'initialize', None) if not callable(initfunc): InitFlg.isInitOk = 1 initfunc = None else: InitFlg.isInitOk = 0 heartbeatfunc = getattr(options, 'heartbeat', None) if not callable(heartbeatfunc): heartbeatfunc = None if heartbeatfunc or initfunc: def serverinit(): hc = 0 if initfunc: try: initfunc(options) InitFlg.isInitOk = 1 except: tylog.error() return while 1: tasklet = stackless.getcurrent()._fttask tasklet.sleepNb(1) try: heartbeatfunc(hc) except: tylog.error() hc = hc + 1 TyTasklet.create([], {"handler": serverinit}) mainloop()
def initConfigMods(self): gamePkgPath = "webmgr.handler.game.G%d" % self.gameId gamePkg = importlib.import_module(gamePkgPath) gamePkgDir = os.path.dirname(gamePkg.__file__) for _, name, _ in pkgutil.iter_modules([gamePkgDir]): tylog.info("BaseActionHandler.initConverters| try init:", name) try: configMod = ConfigMod(name, self.gameId, self.svnTestingUrl, self.svnReleaseUrl, self.teamRoot, gamePkgDir) self.configMods[name] = configMod except: tylog.error("BaseActionHandler.initConverters| name:", name)
def startup(options): logfile = getattr(options, 'logfile', None) if logfile : tylog.info('Open Log File :', logfile) log_path = fsutils.getParentDir(logfile) log_file = fsutils.getLastPathName(logfile) tylog.initLog(log_file, log_path) port = getattr(options, 'httpport', 0) if port > 0 : listenHttp(port) port = getattr(options, 'wsport', 0) if port > 0 : listenWs(port) initfunc = getattr(options, 'initialize', None) if not callable(initfunc) : InitFlg.isInitOk = 1 initfunc = None else: InitFlg.isInitOk = 0 heartbeatfunc = getattr(options, 'heartbeat', None) if not callable(heartbeatfunc) : heartbeatfunc = None if heartbeatfunc or initfunc : def serverinit(): hc = 0 if initfunc : try: initfunc(options) InitFlg.isInitOk = 1 except: tylog.error() return while 1 : tasklet = stackless.getcurrent()._fttask tasklet.sleepNb(1) try: heartbeatfunc(hc) except: tylog.error() hc = hc + 1 TyTasklet.create([], {"handler":serverinit}) mainloop()
def initMods(self, gamePkgDir): tylog.info("ConfigMod.initMods| try import", self.name) pkgPath = "webmgr.handler.game.G%d.%s" % (self.gameId, self.name) pkgDir = os.path.join(gamePkgDir, self.name) mods = {} for _, modname, _ in pkgutil.iter_modules([pkgDir]): try: mods[modname] = importlib.import_module('.' + modname, pkgPath) except: tylog.info("ConfigMod.initMods|import fail" "|name, mod:", self.name, modname) self.converter = mods.get('converter') self.editor = mods.get('editor')
def add_action(action_name, params, username): tylog.info('add_action->', action_name, params, username) actionlistcond.acquire() try: global actnum actnum += 1 if actnum > 9999: actnum = 1 atime = datetime.now().strftime('%Y%m%d_%H%M%S') uuid = atime + '_%04d' % (actnum) act = {'action': action_name, 'params': params, 'uuid': uuid, 'time': atime, 'user': username} actionlist.append(act) return act finally: actionlistcond.release()
def __registerWsEntry(handler, method, entry): # 确定HTTP的API路径 wsgid = entry.get('wsgameid', 0) wscmd = entry.get('wscmd', None) wsact = entry.get('wsact', None) if not isinstance(wscmd, (str, unicode)) or len(wscmd) <= 0: cmdpath = method.__name__ if cmdpath.find('do_cmd_') == 0: cmdpath = cmdpath[6:] while cmdpath.find('__') >= 0: cmdpath = cmdpath.replace('//', '/') cmdpaths = cmdpath.split('_', 1) wscmd = cmdpaths[0] if len(cmdpaths) > 1: wsact = cmdpaths[1] else: wsact = '' entry['wscmd'] = wscmd entry['wsact'] = wsact # 确定是否需要IP过滤 entry['ip_filter'] = __dummyIpFilter if entry['need_ip_filter']: ip_filter = getattr(handler, 'ip_filter', None) if callable(ip_filter): entry['ip_filter'] = ip_filter gamecmds = __ws_commands.get(wsgid, None) if gamecmds == None: gamecmds = {} __ws_commands[wsgid] = gamecmds wscmds = gamecmds.get(wscmd, None) if wscmds == None: wscmds = {} gamecmds[wsgid] = wscmds wspath = '%s-%s-%s' % (str(wsgid), str(wscmd), str(wsact)) if wsact in wscmds: tylog.info('WARRING !! the ws command already defined !! wspath=' + wspath) wscmds[wsact] = (method, entry) tylog.info('HTTP Add Entry ->wscommand=,', wspath, 'method=', method) return wspath
def __registerWsEntry(handler, method, entry): # 确定HTTP的API路径 wsgid = entry.get('wsgameid', 0) wscmd = entry.get('wscmd', None) wsact = entry.get('wsact', None) if not isinstance(wscmd, (str, unicode)) or len(wscmd) <= 0 : cmdpath = method.__name__ if cmdpath.find('do_cmd_') == 0 : cmdpath = cmdpath[6:] while cmdpath.find('__') >= 0 : cmdpath = cmdpath.replace('//', '/') cmdpaths = cmdpath.split('_', 1) wscmd = cmdpaths[0] if len(cmdpaths) > 1 : wsact = cmdpaths[1] else: wsact = '' entry['wscmd'] = wscmd entry['wsact'] = wsact # 确定是否需要IP过滤 entry['ip_filter'] = __dummyIpFilter if entry['need_ip_filter'] : ip_filter = getattr(handler, 'ip_filter', None) if callable(ip_filter) : entry['ip_filter'] = ip_filter gamecmds = __ws_commands.get(wsgid, None) if gamecmds == None : gamecmds = {} __ws_commands[wsgid] = gamecmds wscmds = gamecmds.get(wscmd, None) if wscmds == None : wscmds = {} gamecmds[wsgid] = wscmds wspath = '%s-%s-%s' % (str(wsgid), str(wscmd), str(wsact)) if wsact in wscmds : tylog.info('WARRING !! the ws command already defined !! wspath=' + wspath) wscmds[wsact] = (method, entry) tylog.info('HTTP Add Entry ->wscommand=,', wspath, 'method=' , method) return wspath
def doFinish(content, fheads, debugreturn=True): request = getRequest() rpath = request.path if debugreturn: debugcontent = content if len(debugcontent) > 128 and debugcontent[0] != '{': debugcontent = repr(debugcontent[0:128]) + '......' if TRACE_RESPONSE: tylog.info('HTTPRESPONSE', rpath, debugcontent) else: if TRACE_RESPONSE: tylog.info('HTTPRESPONSE', rpath) if getattr(request, 'finished', 0) == 1: tylog.error('HTTPRESPONSE already finished !!', rpath) return request.setHeader('Content-Length', len(content)) try: for k, v in fheads.items(): request.setHeader(k, v) except: tylog.error(rpath) try: request.write(content) except: try: request.write(content.encode('utf8')) except: tylog.error(rpath) try: request.channel.persistent = 0 except: pass try: request.finish() except: if TRACE_RESPONSE: tylog.error(rpath) setattr(request, 'finished', 1)
def doFinish(content, fheads, debugreturn=True): request = getRequest() rpath = request.path if debugreturn : debugcontent = content if len(debugcontent) > 128 and debugcontent[0] != '{': debugcontent = repr(debugcontent[0:128]) + '......' if TRACE_RESPONSE : tylog.info('HTTPRESPONSE', rpath, debugcontent) else: if TRACE_RESPONSE : tylog.info('HTTPRESPONSE', rpath) if getattr(request, 'finished', 0) == 1 : tylog.error('HTTPRESPONSE already finished !!', rpath) return request.setHeader('Content-Length', len(content)) try: for k, v in fheads.items() : request.setHeader(k, v) except: tylog.error(rpath) try: request.write(content) except: try: request.write(content.encode('utf8')) except: tylog.error(rpath) try: request.channel.persistent = 0 except: pass try: request.finish() except: if TRACE_RESPONSE : tylog.error(rpath) setattr(request, 'finished', 1)
def add_action(action_name, params, username): tylog.info('add_action->', action_name, params, username) actionlistcond.acquire() try: global actnum actnum += 1 if actnum > 9999: actnum = 1 atime = datetime.now().strftime('%Y%m%d_%H%M%S') uuid = atime + '_%04d' % (actnum) act = { 'action': action_name, 'params': params, 'uuid': uuid, 'time': atime, 'user': username } actionlist.append(act) return act finally: actionlistcond.release()
def __init__(self, config_json): self._timelist = [] self._dayslist = [] try: if isinstance(config_json, basestring): self._config = json.loads(config_json) else: self._config = config_json # 整理一天内的时间点列表 if "list" in self._config["times_in_day"]: lt = self._config["times_in_day"]["list"] for l in lt: lg = l.split(":") hour = int(lg[0]) minu = int(lg[1]) self._timelist.append(datetime.time(hour, minu, 0)) else: first = self._config["times_in_day"]["first"] inter = int(self._config["times_in_day"]["interval"]) count = self._config["times_in_day"]["count"] lg = first.split(":") hour = int(lg[0]) minu = int(lg[1]) ftime = datetime.time(hour, minu, 0) self._timelist.append(ftime) dtime = datetime.timedelta(minutes=inter) for x in xrange(count): ftime = (datetime.datetime.combine(datetime.date(1, 1, 1), ftime) + dtime).time() if ftime > self._timelist[0]: self._timelist.append(ftime) else: ftlog.info( "warning!!! times_in_day count too large!!!", x) break # 整理天列表 if "list" in self._config["days"]: ld = self._config["days"]["list"] for d in ld: self._dayslist.append( datetime.datetime.strptime(d, "%Y%m%d")) else: first = self._config["days"]["first"] inter = self._config["days"]["interval"] ninter = int(inter[0]) iinter = inter[1] if iinter == 'd': intdelta = relativedelta(days=ninter) if iinter == 'w': intdelta = relativedelta(weeks=ninter) if iinter == 'm': intdelta = relativedelta(months=ninter) if iinter == 'y': intdelta = relativedelta(years=ninter) count = self._config["days"]["count"] if count > self.MAX_DAY_COUNT: count = self.MAX_DAY_COUNT ftlog.info("warning!!! days count too large!!!", count) firsts = [] if not first: firsts.append(first) elif isinstance(first, (unicode, str)): firsts.append(first) elif isinstance(first, list): firsts = first for first in firsts: if first: fday = datetime.datetime.strptime(first, "%Y%m%d") else: fday = datetime.datetime.now() self._dayslist.append(fday) for x in xrange(count): fday = fday + intdelta self._dayslist.append(fday) self._dayslist.sort() except: ftlog.error("parse config json error:", config_json) self._config = None
def __init__(self, config_json): self._timelist = [] self._dayslist = [] try: if isinstance(config_json, basestring): self._config = json.loads(config_json) else: self._config = config_json # 整理一天内的时间点列表 if "list" in self._config["times_in_day"]: lt = self._config["times_in_day"]["list"] for l in lt: lg = l.split(":") hour = int(lg[0]) minu = int(lg[1]) self._timelist.append(datetime.time(hour, minu, 0)) else: first = self._config["times_in_day"]["first"] inter = int(self._config["times_in_day"]["interval"]) count = self._config["times_in_day"]["count"] lg = first.split(":") hour = int(lg[0]) minu = int(lg[1]) ftime = datetime.time(hour, minu, 0) self._timelist.append(ftime) dtime = datetime.timedelta(minutes=inter) for x in xrange(count): ftime = (datetime.datetime.combine(datetime.date(1, 1, 1), ftime) + dtime).time() if ftime > self._timelist[0]: self._timelist.append(ftime) else: ftlog.info("warning!!! times_in_day count too large!!!", x) break # 整理天列表 if "list" in self._config["days"]: ld = self._config["days"]["list"] for d in ld: self._dayslist.append(datetime.datetime.strptime(d, "%Y%m%d")) else: first = self._config["days"]["first"] inter = self._config["days"]["interval"] ninter = int(inter[0]) iinter = inter[1] if iinter == 'd': intdelta = relativedelta(days=ninter) if iinter == 'w': intdelta = relativedelta(weeks=ninter) if iinter == 'm': intdelta = relativedelta(months=ninter) if iinter == 'y': intdelta = relativedelta(years=ninter) count = self._config["days"]["count"] if count > self.MAX_DAY_COUNT: count = self.MAX_DAY_COUNT ftlog.info("warning!!! days count too large!!!", count) firsts=[] if not first: firsts.append(first) elif isinstance(first, (unicode, str)): firsts.append(first) elif isinstance(first, list): firsts=first for first in firsts: if first: fday = datetime.datetime.strptime(first, "%Y%m%d") else: fday = datetime.datetime.now() self._dayslist.append(fday) for x in xrange(count): fday = fday + intdelta self._dayslist.append(fday) self._dayslist.sort() except: ftlog.error("parse config json error:", config_json) self._config = None
def handlerWsRequest(wsprotocol): if InitFlg.isInitOk != 1: mo = MsgPack() mo.setError(1, 'ws system not startup') mo = __stringifyResponse(0, mo) wsprotocol.sendData(mo) wsprotocol.wsClose() return mo = None try: tasklet = stackless.getcurrent()._fttask session = tasklet.session msg = tasklet.run_args['pack'] session['isws'] = 1 wsgid = msg.getParamInt() wscmd = msg.getCmd() wsact = msg.getParamAct() rpath = '%s-%s-%s' % (str(wsgid), str(wscmd), str(wsact)) if TRACE_RESPONSE: tylog.info('WSREQUEST', rpath, msg) # 当前服务处理 funws, entry = None, None gamecmds = __ws_commands.get(wsgid, None) if gamecmds != None: wscmds = gamecmds.get(wscmd, None) if wscmds != None: funws, entry = wscmds.get(wsact, (None, None)) if funws == None or entry == None: mo = MsgPack() mo.setResult('gameId', wsgid) mo.setResultActCmd(wsact, wscmd) mo.setError(1, 'the command not inplement !') mo = __stringifyResponse(entry['jsonp'], mo) wsprotocol.sendData(mo) return # 未找到对应的调用失败, 返回 # IP 地址过滤 if entry['need_ip_filter']: ip = getClientIp() mo = entry['ip_filter'](ip) if mo: mo = __stringifyResponse(entry['jsonp'], mo) wsprotocol.sendData(mo) wsprotocol.wsClose() return # IP 过滤失败, 返回 # 执行动态调用 try: mo = funws() if mo == None: mo = MsgPack() mo.setResult('gameId', wsgid) mo.setResultActCmd(wsact, wscmd) mo.setError(1, 'ws api return None') except: tylog.error() mo = MsgPack() mo.setResult('gameId', wsgid) mo.setResultActCmd(wsact, wscmd) mo.setError(1, 'ws api exception') mo = __stringifyResponse(entry['jsonp'], mo) wsprotocol.sendData(mo) except: tylog.error() mo = MsgPack() mo.setError(1, 'system exception return') mo = __stringifyResponse(0, mo) wsprotocol.sendData(mo)
def __init__(self, options): self.options = options self.gameConfPath = fsutils.appendPath(self.options.pokerpath, 'game/6') ftlog.info('DizhuActionHandler.__init__ options=', self.options, 'gameConfPath=', self.gameConfPath)
def get_incidence(): data = {"test": 'get done!'} tylog.info('model.get_incidence->', data) return data
def set_incidence(data): tylog.info('model.set_incidence->', data)
def handlerWsRequest(wsprotocol): if InitFlg.isInitOk != 1: mo = MsgPack() mo.setError(1, 'ws system not startup') mo = __stringifyResponse(0, mo) wsprotocol.sendData(mo) wsprotocol.wsClose() return mo = None try: tasklet = stackless.getcurrent()._fttask session = tasklet.session msg = tasklet.run_args['pack'] session['isws'] = 1 wsgid = msg.getParamInt() wscmd = msg.getCmd() wsact = msg.getParamAct() rpath = '%s-%s-%s' % (str(wsgid), str(wscmd), str(wsact)) if TRACE_RESPONSE : tylog.info('WSREQUEST', rpath, msg) # 当前服务处理 funws, entry = None, None gamecmds = __ws_commands.get(wsgid, None) if gamecmds != None : wscmds = gamecmds.get(wscmd, None) if wscmds != None : funws, entry = wscmds.get(wsact, (None, None)) if funws == None or entry == None: mo = MsgPack() mo.setResult('gameId', wsgid) mo.setResultActCmd(wsact, wscmd) mo.setError(1, 'the command not inplement !') mo = __stringifyResponse(entry['jsonp'], mo) wsprotocol.sendData(mo) return # 未找到对应的调用失败, 返回 # IP 地址过滤 if entry['need_ip_filter'] : ip = getClientIp() mo = entry['ip_filter'](ip) if mo : mo = __stringifyResponse(entry['jsonp'], mo) wsprotocol.sendData(mo) wsprotocol.wsClose() return # IP 过滤失败, 返回 # 执行动态调用 try: mo = funws() if mo == None: mo = MsgPack() mo.setResult('gameId', wsgid) mo.setResultActCmd(wsact, wscmd) mo.setError(1, 'ws api return None') except: tylog.error() mo = MsgPack() mo.setResult('gameId', wsgid) mo.setResultActCmd(wsact, wscmd) mo.setError(1, 'ws api exception') mo = __stringifyResponse(entry['jsonp'], mo) wsprotocol.sendData(mo) except: tylog.error() mo = MsgPack() mo.setError(1, 'system exception return') mo = __stringifyResponse(0, mo) wsprotocol.sendData(mo)