Exemplo n.º 1
0
    def do_http_texas_commit(self, branch, commitlog):
        self._initBase()
        ftlog.debug("do_http_texas_commit branch, commitlog:", branch, commitlog)
        if branch == 'testing':
            src = teamCfgDir
            tgt = testingDir
        elif branch == 'release':
            src = testingDir
            tgt = releaseDir

            
        outputs = ['提交到 '+branch]
        outputs.append('提交日志:\n'+ commitlog + '\n')

        sh_file = os.path.join(os.path.dirname(__file__), "commit.sh")
        cmd = 'bash %s %s %s %s %s' % (sh_file, src, tgt, "wangt", "g01dfish")
        ftlog.debug("do_http_texas_commit| cmd:", cmd)
        sh_output = os.popen(cmd).read()
        ftlog.debug("do_http_texas_commit| sh_output:", sh_output)
        outputs.append(sh_output)


        ftlog.debug("do_http_texas_commit branch, tgt, commitlog:", branch, tgt, commitlog)
        cmd, status, output = self._svnCmd(teamRoot, 'commit', tgt, '-m', '"%s"' % commitlog)
        ftlog.debug("do_http_texas_commit| branch:", branch,
                    "| status, output:", status, output)
        outputs.append('svn 提交输出:\n'+ output + '\n')


        output = ('\n\n').join(outputs)

        mo = MsgPack()
        mo.setCmd('texas_commit')
        mo.setResult('output', output.replace(' ', '&nbsp;').replace('\n', '<br />'))
        return mo 
Exemplo n.º 2
0
 def do_http_texas_get_match_time(self):
     '''获取所有比赛的所有场次的所有开赛时间'''
     self._initBase()
     days = int(runhttp.getParamStr('days', 5))
     ftlog.debug("TexasActionHandler.do_http_texas_get_match_time", "days:", days)
     match_time = self.calcAllStartTimes(days)
     mo = MsgPack()
     mo.setCmd('match_time')
     mo.setResult('match_time', match_time)
     return mo
Exemplo n.º 3
0
    def do_http_t3flush_get_json_file(self, jsonfile):
        self._initBase()
        ftlog.debug("do_http_t3flush_get_json_file jsonfile:", jsonfile)
        if fsutils.fileExists(jsonfile):
            datas = fsutils.readJsonFile(jsonfile)
        else:
            datas = {'error': 'file "%s" not existed' % jsonfile}

        mo = MsgPack()
        mo.setCmd('json_file_data')
        mo.setResult('isOk', True)
        mo.setResult('jsonfile', jsonfile)
        mo.setResult('datas', datas)
        return mo
Exemplo n.º 4
0
    def gen_t3flush_room_json(self):
        self._initBase()

        xlsfile = fsutils.appendPath(teamCfgDir, 'room.xls')
        jsonallfile = fsutils.appendPath(teamCfgDir, '0.json.all')
        jsonfile = fsutils.appendPath(teamCfgDir, 'room.json')
        jsonfileprev = fsutils.appendPath(teamCfgDir, 'room.json.prev')

        self._svnCmd(teamCfgDir, 'update', xlsfile)
        # 获取历史记录 svn log
        _, _, svnlog = self._svnCmd(teamCfgDir, 'log', '-l 5', xlsfile)
        logcontent = '\n'.join([
            line for line in svnlog.split('\n') if not line.startswith('-----')
        ])
        svnlog = svnlog.replace('\n', '<br/>')

        commands.getstatusoutput("rm -f [0-9]*.json")

        try:
            room_conf_generator.gen_split_file(xlsfile, teamCfgDir)
        except Exception, e:
            errstr = traceback.format_exc()
            mo = MsgPack()
            mo.setCmd('json_file_data')
            mo.setResult('isOk', False)
            mo.setResult("error", errstr)
            return mo
Exemplo n.º 5
0
def getMsgPack(keys=None):
    request = getRequest()
    args = request.args
    msg = MsgPack()
    if keys == None :
        keys = args.keys()
    for key in keys :
        if key in args :
            value = args[key][0]
        else:
            value = ''
        msg.setParam(key, value.strip())
    rpath = request.path.lower().replace('/', '_')
    msg.setCmd(rpath[1:])
    return msg
Exemplo n.º 6
0
    def gen_texas_room_json(self):
        self._initBase()

        xlsfile = fsutils.appendPath(teamCfgDir, 'room.xls')
        jsonallfile = fsutils.appendPath(teamCfgDir, '0.json.all')
        jsonfile = fsutils.appendPath(teamCfgDir, 'room.json')
        jsonfileprev = fsutils.appendPath(teamCfgDir, 'room.json.prev')

        self._svnCmd(teamCfgDir, 'update', xlsfile)
        # 获取历史记录 svn log
        _, _, svnlog = self._svnCmd(teamCfgDir, 'log', '-l 5', xlsfile)
        logcontent = '\n'.join([line for line in svnlog.split('\n') if not line.startswith('-----')])
        svnlog = svnlog.replace('\n', '<br/>')

        commands.getstatusoutput("rm -f [0-9]*.json")

        try:
            room_conf_generator.gen_split_file(xlsfile, teamCfgDir)
        except Exception, e:
            errstr = traceback.format_exc()
            mo = MsgPack()
            mo.setCmd('json_file_data')
            mo.setResult('isOk', False)
            mo.setResult("error", errstr)
            return mo
Exemplo n.º 7
0
    def do_http_texas_get_json_file(self, jsonfile):
        self._initBase()
        ftlog.debug("do_http_texas_gen_json_file jsonfile:", jsonfile)
        if fsutils.fileExists(jsonfile) :
            datas = fsutils.readJsonFile(jsonfile)
        else:
            datas = {'error': 'file "%s" not existed' % jsonfile}

        mo = MsgPack()
        mo.setCmd('json_file_data')
        mo.setResult('isOk', True)
        mo.setResult('jsonfile', jsonfile)
        mo.setResult('datas', datas)
        return mo 
Exemplo n.º 8
0
    def do_http_get_action_log(self, action_uuid, line_num):
        lines = acthistory.get_action_log(self.options, action_uuid, line_num)
        for x in xrange(len(lines)):
            try:
                json.dumps([lines[x]])
            except:
                lines[x] = 'repr(' + repr(lines[x]) + ')'

        mo = MsgPack()
        mo.setCmd('action_log')
        mo.setResult('uuid', action_uuid)
        mo.setResult('lines', lines)
        return mo
Exemplo n.º 9
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
Exemplo n.º 10
0
 def do_http_t3flush_get_match_time(self):
     '''获取所有比赛的所有场次的所有开赛时间'''
     self._initBase()
     days = int(runhttp.getParamStr('days', 5))
     ftlog.debug("T3flushActionHandler.do_http_t3flush_get_match_time",
                 "days:", days)
     match_time = self.calcAllStartTimes(days)
     mo = MsgPack()
     mo.setCmd('match_time')
     mo.setResult('match_time', match_time)
     return mo
Exemplo n.º 11
0
 def do_http_get_process_list(self):
     jfile = fsutils.appendPath(self.options.pokerpath, '._process_.json')
     if fsutils.fileExists(jfile):
         datas = fsutils.readJsonFile(jfile)
     else:
         datas = []
     datas.sort(key=lambda x: x['type'] + x['id'])
     mo = MsgPack()
     mo.setCmd('process_list')
     mo.setResult('datas', datas)
     return mo
Exemplo n.º 12
0
    def do_http_set_json_file(self, jsonfile, jsondata):
        jfile = fsutils.appendPath(self.options.pokerpath, jsonfile)
        jsondata = json.dumps(jsondata,
                              indent=2,
                              separators=(', ', ' : '),
                              sort_keys=True,
                              ensure_ascii=False)
        lines = jsondata.split('\n')
        for x in xrange(len(lines)):
            lines[x] = lines[x].rstrip()
        jsondata = '\n'.join(lines)

        fsutils.writeFile('', jfile, jsondata)
        datas = fsutils.readJsonFile(jfile)
        mo = MsgPack()
        mo.setCmd('json_file_data')
        mo.setResult('jsonfile', jsonfile)
        mo.setResult('datas', datas)
        return mo
Exemplo n.º 13
0
 def do_http_get_json_file(self, jsonfile):
     jfile = fsutils.appendPath(self.options.pokerpath, jsonfile)
     print "DEBUG", "self.options.pokerpath:", self.options.pokerpath, "jsonfile:", jsonfile, 'jfile:', jfile
     if fsutils.fileExists(jfile):
         datas = fsutils.readJsonFile(jfile)
     else:
         if jsonfile in ('project.json', 'server.json'):
             datas = []
         # elif jsonfile in model.models:
         #     method = model.models[jsonfile].get('get')
         #     if method:
         #         datas = method()
         else:
             datas = {}
     mo = MsgPack()
     mo.setCmd('json_file_data')
     mo.setResult('jsonfile', jsonfile)
     mo.setResult('datas', datas)
     return mo
Exemplo n.º 14
0
def getMsgPack(keys=None):
    request = getRequest()
    args = request.args
    msg = MsgPack()
    if keys == None:
        keys = args.keys()
    for key in keys:
        if key in args:
            value = args[key][0]
        else:
            value = ''
        msg.setParam(key, value.strip())
    rpath = request.path.lower().replace('/', '_')
    msg.setCmd(rpath[1:])
    return msg
Exemplo n.º 15
0
    def do_http_t3flush_commit(self, branch, commitlog):
        self._initBase()
        ftlog.debug("do_http_t3flush_commit branch, commitlog:", branch,
                    commitlog)
        if branch == 'testing':
            src = teamCfgDir
            tgt = testingDir
        elif branch == 'release':
            src = testingDir
            tgt = releaseDir

        outputs = ['提交到 ' + branch]
        outputs.append('提交日志:\n' + commitlog + '\n')

        sh_file = os.path.join(os.path.dirname(__file__), "commit.sh")
        cmd = 'bash %s %s %s %s %s' % (sh_file, src, tgt, "wangt", "g01dfish")
        ftlog.debug("do_http_t3flush_commit| cmd:", cmd)
        sh_output = os.popen(cmd).read()
        ftlog.debug("do_http_t3flush_commit| sh_output:", sh_output)
        outputs.append(sh_output)
        outputs.append('复制文件:\n' + '%s => %s' % (src, tgt) + '\n')

        ftlog.debug("do_http_t3flush_commit branch, tgt, commitlog, :", branch,
                    tgt, commitlog)
        cmd, status, output = self._svnCmd(teamRoot, 'commit', tgt, '-m',
                                           '"%s"' % commitlog)
        ftlog.debug("do_http_t3flush_commit| branch:", branch,
                    "| status, output:", status, output)
        outputs.append('svn 提交输出:\n' + output + '\n')
        output = ('\n\n').join(outputs)
        #output = '暂时不实现\n不真的提交'

        mo = MsgPack()
        mo.setCmd('t3flush_commit')
        mo.setResult('output',
                     output.replace(' ', '&nbsp;').replace('\n', '<br />'))
        return mo
Exemplo n.º 16
0
    def do_http_texas_precommit(self, branch):
        self._initBase()
        ftlog.debug("do_http_texas_precommit branch:", branch)
        if branch == 'testing':
            jsonfile        = os.path.join(teamCfgDir, '0.json.all')
            jsonfileprev    = os.path.join(testingDir, '0.json.all')
        elif branch == 'release':
            jsonfile        = os.path.join(testingDir, '0.json.all')
            jsonfileprev    = os.path.join(releaseDir, '0.json.all')
            
        _, _, svnlog = self._svnCmd(teamRoot, 'log', '-l 5', jsonfileprev)
        svnlog = '\n'.join([line for line in svnlog.split('\n') if not line.startswith('------')])

        mo = MsgPack()
        mo.setCmd('texas_precommit')
        mo.setResult('isOk', True)
        mo.setResult('jsonfile', jsonfile)
        mo.setResult('jsonfileprev', jsonfileprev)
        mo.setResult('svnlog', svnlog)
        return mo 
Exemplo n.º 17
0
 def do_http_remove_action(self, action_uuids):
     acthistory.remove_action(self.options, action_uuids)
     mo = MsgPack()
     mo.setCmd('remove_action')
     mo.setResult('ok', 1)
     return mo
Exemplo n.º 18
0
    def do_http_debug_action(self, action):

        if action == 'redis_clear_all':
            result = redisdata.redis_clear_all(self.options)

        userId = runhttp.getParamInt('userId', 0)
        gameId = runhttp.getParamInt('gameId', 0)
        key = runhttp.getParamStr('key', '')
        value = runhttp.getParamStr('value', '')

        if action == 'redis_search_all_userdata':
            result = redisdata.redis_search_all_userdata(self.options, userId)

        if action == 'html_redirect':
            datas = redisdata._getLastOkDefines(self.options)
            httpgame = datas['pokerdict']['http_game']
            rurl = runhttp.getParamStr('url')
            if os.environ.get('RUN_IN_DOCKER', 0):
                # 在开发docker模式下,需要替换为外部HALL37HTTP端口号(此端口由nginx代理服务)
                refhost = runhttp.getParamStr('refhost')
                tks = refhost.split(':')
                tks[-1] = os.environ.get('PORT_NGINX', '80')
                httpgame = ':'.join(tks)
            result = rurl.replace('${http_game}', httpgame)

        if action == 'redis_get_userdata':
            result = redisdata.redis_get_userdata(self.options, userId)

        if action == 'redis_set_userdata':
            result = redisdata.redis_set_userdata(self.options, userId, key,
                                                  value)

        if action == 'redis_get_gamedata':
            result = redisdata.redis_get_gamedata(self.options, userId, gameId)

        if action == 'redis_set_gamedata':
            result = redisdata.redis_set_gamedata(self.options, userId, gameId,
                                                  key, value)

        if action == 'redis_get_map_clientid':
            result = redisdata.redis_get_config(self.options,
                                                'poker:map.clientid')

        if action == 'redis_get_map_productid':
            result = redisdata.redis_get_config(self.options,
                                                'poker:map.productid')

        if action == 'redis_get_map_activityid':
            result = redisdata.redis_get_config(self.options,
                                                'poker:map.activityid')

        if action == 'redis_get_map_evnetid':
            result = redisdata.redis_get_config(self.options,
                                                'poker:map.bieventid')

        if action == 'redis_del_userdata':
            result = redisdata.redis_del_userdata(self.options, userId)

        if action == 'redis_del_gamedata':
            result = redisdata.redis_del_gamedata(self.options, userId, gameId)

        if action == 'redis_del_day1st':
            result = redisdata.redis_del_weakdata(self.options, userId, False)

        if action == 'redis_del_daylogin':
            result = redisdata.redis_del_weakdata(self.options, userId, True)

        if action == 'redis_get_usertime':
            result = redisdata.redis_get_usertime(self.options, userId)

        if action == 'redis_command':
            cmdline = runhttp.getParamStr('command', '')
            cmdline = strutil.loads(cmdline)
            ralias = runhttp.getParamStr('redisalias', '')
            roomId = runhttp.getParamInt('roomId', 0)
            result = redisdata.redis_do_command(self.options, userId, roomId,
                                                ralias, cmdline)

        datas = redisdata._getLastOkDefines(self.options)
        httpgame = datas['pokerdict']['http_game']
        if action == 'putmsg':
            httpgame = httpgame + '/v1/putmsg'
            result = tyhttp.dohttpquery(httpgame, runhttp.getDict())

        if action == 'get_room_info':
            httpgame = httpgame + '/_http_manager_get_room_details'
            result = tyhttp.dohttpquery(httpgame, runhttp.getDict())

        if action == 'hotfix_code':
            from optparse import Values
            options = Values()
            setattr(options, 'poker_path', self.options.pokerpath)
            setattr(options, 'hotfixpy', runhttp.getParamStr('hotfixpy'))
            setattr(options, 'hotfixwait', 1)
            setattr(options, 'serverIds', runhttp.getParamStr('serverIds'))
            result = hotfix.action(options, 0)

        if isinstance(result, (long, int, float, bool)):
            result = str(result)
        if isinstance(result, (list, tuple, dict, set)):
            result = json.dumps(result,
                                indent=2,
                                sort_keys=True,
                                ensure_ascii=False)
        if not isinstance(result, (str, unicode)):
            result = str(result)
        result = result.replace('<', '&lt;')
        result = result.replace('>', '&gt;')
        result = result.replace('\r', '')
        result = result.replace('\n', '<br>')
        result = result.replace('\\n', '<br>')
        result = result.replace(' ', '&nbsp;')
        result = result.replace('\\\\x', '\\x')
        mo = MsgPack()
        mo.setCmd(action)
        mo.setResult('ok', 1)
        mo.setResult('text', result)
        return mo
Exemplo n.º 19
0
    def do_http_model_list(self):
        mj = getResourcePath('menu.json')
        models = fsutils.readJsonFile(mj)
        # 读取game目录下的游戏目录
        otherConfPath = fsutils.appendPath(self.options.pokerpath, 'game')
        otherconf = os.listdir(otherConfPath)
        games = []
        for gid in otherconf:
            try:
                # 创建game-游戏配置目录。由于其它游戏的配置目录都是空, 就都跳过
                if int(gid) not in [8, 30, 39]:
                    continue

                gid = str(int(gid))
                children = []
                tylog.debug("do_http_model_list|get game mode|", gid=gid)
                self.getGameConfiger(int(gid), children)
                if children:
                    games.append({'text': 'game-' + gid, 'children': children})

                # # 创建该游戏下面的所有配置目录
                # gameConfigPath = fsutils.appendPath(otherConfPath, gid)
                # gameConfigs = os.listdir(gameConfigPath)
                # for gc in gameConfigs:
                #     if str(gc) != '.svn':
                #         children.append({'text': str(gc), 'attributes':{
                #                 "purl" : "model/config/game/" + gid + '/' + gc + '.html'
                #             }}
                #         )
            except:
                tylog.error("do_http_model_list|get game mode error|", gid=gid)
        models[0]['children'].extend(games)
        # models[0]['children'].append({'text': '查看模板关联', 'attributes':{
        #                         "purl" : "model/config/game/incidence.html"
        #                     }})

        # 动态测试工具
        debugs = []
        models.append({'text': '调试工具', 'children': debugs})

        webroot = fsutils.appendPath(self.options.workpath, 'webroot', 'model',
                                     'debug')
        hfs = os.listdir(webroot)
        for hf in hfs:
            if hf.endswith('.html'):
                hc = fsutils.readFile(webroot + '/' + hf)
                t = self._findTitle(hc)
                if t:
                    purl = "model/debug/" + hf
                    debugs.append({'text': t, 'attributes': {"purl": purl}})
        debugs.sort(key=lambda x: x['text'])
        mo = MsgPack()
        mo.setCmd('model_list')
        mo.setResult('models', models)
        mo.setResult('pokerpath', self.options.pokerpath)
        mo.setResult('mgrpath', self.options.workpath)
        mo.setResult('localip', fsutils.getLocalMachineIp())
        mo.setResult(
            'title',
            '.'.join(fsutils.getLocalMachineIp()[0].split('.')[2:]) + '管理器')
        return mo
Exemplo n.º 20
0
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)
Exemplo n.º 21
0
 def jsonrsp(self, cmd, **result):
     msg = MsgPack()
     msg.setCmd(cmd)
     msg.setKey('result', result)
     return msg
Exemplo n.º 22
0
 def do_http_get_action_list(self):
     actions = acthistory.get_action_list(self.options)
     mo = MsgPack()
     mo.setCmd('action_list')
     mo.setResult('actions', actions)
     return mo
Exemplo n.º 23
0
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)
Exemplo n.º 24
0
 def parseData(self, data):
     mpack = MsgPack()
     mpack.unpack(data)
     return mpack
Exemplo n.º 25
0
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)
Exemplo n.º 26
0
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)
Exemplo n.º 27
0
 def do_http_info(self):
     mo = MsgPack()
     mo.setCmd('info')
     return mo
Exemplo n.º 28
0
class T3flushActionHandler(object):
    def __init__(self, options):
        self.options = options

    @markHttpRequestEntry(jsonp=1)
    def do_http_t3flush_gen_json_file(self, jsonfile):
        self._initBase()
        ftlog.debug('do_http_t3flush_gen_json_file', jsonfile)
        if jsonfile == 'game/39/room/0.json':
            return self.gen_t3flush_room_json()

    @markHttpRequestEntry(jsonp=1)
    def do_http_t3flush_get_json_file(self, jsonfile):
        self._initBase()
        ftlog.debug("do_http_t3flush_get_json_file jsonfile:", jsonfile)
        if fsutils.fileExists(jsonfile):
            datas = fsutils.readJsonFile(jsonfile)
        else:
            datas = {'error': 'file "%s" not existed' % jsonfile}

        mo = MsgPack()
        mo.setCmd('json_file_data')
        mo.setResult('isOk', True)
        mo.setResult('jsonfile', jsonfile)
        mo.setResult('datas', datas)
        return mo

    @markHttpRequestEntry()
    def do_http_t3flush_precommit(self, branch):
        self._initBase()
        ftlog.debug("do_http_t3flush_precommit branch:", branch)
        if branch == 'testing':
            jsonfile = os.path.join(teamCfgDir, '0.json.all')
            jsonfileprev = os.path.join(testingDir, '0.json.all')
        elif branch == 'release':
            jsonfile = os.path.join(testingDir, '0.json.all')
            jsonfileprev = os.path.join(releaseDir, '0.json.all')

        _, _, svnlog = self._svnCmd(teamRoot, 'log', '-l 5', jsonfileprev)
        svnlog = '\n'.join([
            line for line in svnlog.split('\n')
            if not line.startswith('------')
        ])

        mo = MsgPack()
        mo.setCmd('t3flush_precommit')
        mo.setResult('isOk', True)
        mo.setResult('jsonfile', jsonfile)
        mo.setResult('jsonfileprev', jsonfileprev)
        mo.setResult('svnlog', svnlog)
        return mo

    @markHttpRequestEntry()
    def do_http_t3flush_commit(self, branch, commitlog):
        self._initBase()
        ftlog.debug("do_http_t3flush_commit branch, commitlog:", branch,
                    commitlog)
        if branch == 'testing':
            src = teamCfgDir
            tgt = testingDir
        elif branch == 'release':
            src = testingDir
            tgt = releaseDir

        outputs = ['提交到 ' + branch]
        outputs.append('提交日志:\n' + commitlog + '\n')

        sh_file = os.path.join(os.path.dirname(__file__), "commit.sh")
        cmd = 'bash %s %s %s %s %s' % (sh_file, src, tgt, "wangt", "g01dfish")
        ftlog.debug("do_http_t3flush_commit| cmd:", cmd)
        sh_output = os.popen(cmd).read()
        ftlog.debug("do_http_t3flush_commit| sh_output:", sh_output)
        outputs.append(sh_output)
        outputs.append('复制文件:\n' + '%s => %s' % (src, tgt) + '\n')

        ftlog.debug("do_http_t3flush_commit branch, tgt, commitlog, :", branch,
                    tgt, commitlog)
        cmd, status, output = self._svnCmd(teamRoot, 'commit', tgt, '-m',
                                           '"%s"' % commitlog)
        ftlog.debug("do_http_t3flush_commit| branch:", branch,
                    "| status, output:", status, output)
        outputs.append('svn 提交输出:\n' + output + '\n')
        output = ('\n\n').join(outputs)
        #output = '暂时不实现\n不真的提交'

        mo = MsgPack()
        mo.setCmd('t3flush_commit')
        mo.setResult('output',
                     output.replace(' ', '&nbsp;').replace('\n', '<br />'))
        return mo

    def _initBase(self):
        ''' 初始化一些基本配置 '''

        if getattr(self.options, 't3flushTeamConfInited', False):
            return

        _datas = redisdata._getLastOkDefines(self.options)
        projects_path = _datas['pokerdict'][
            'projects_path']  # 源码目录。一般为: /home/tyhall/hall37/source

        pokerpath = self.options.pokerpath  # 也就是配置目录。一般为 /home/tyhall/hall37/source/config
        teamRoot = os.path.join(projects_path, 't3flush-team')
        runningDir = os.path.join(pokerpath, 'game/39/room/')

        ftlog.debug('T3flushActionHandler._initBase >>|',
                    'projects_path, teamRoot, runningDir:', projects_path,
                    teamRoot, runningDir)

        if not os.path.exists(teamRoot):
            ftlog.debug('create teamRoot:', teamRoot)
            fsutils.makePath(teamRoot)

            self._svnCmd(teamRoot, 'checkout', teamConfUrl, 'team')
            self._svnCmd(teamRoot, 'checkout', roomConfTestingUrl, 'testing')
            self._svnCmd(teamRoot, 'checkout', roomConfReleaseUrl, 'release')

        initDirs(teamRoot, runningDir)

        self.options.t3flushTeamConfInited = True

    def _svnCmd(self, workingpath, svnCmd, *svnArgs):
        print 'DEBUG t3flushActionHandler._svnCmd <<| workingpath, svnCmd, svnArgs', workingpath, svnCmd, svnArgs
        svnau = '--username wangt --password g01dfish --no-auth-cache'
        cmd = ['cd ' + workingpath]
        cmd.append('export LANG=en_US.UTF-8')
        cmd.append(' '.join(['svn', svnCmd, '--non-interactive', svnau] +
                            list(svnArgs)))

        cmd = ';'.join(cmd)
        status, output = commands.getstatusoutput(cmd)
        ftlog.debug('T3flushActionHandler._svnCmd >>| cmd, status, output:',
                    cmd, status, output)
        return cmd, status, output

    def gen_t3flush_room_json(self):
        self._initBase()

        xlsfile = fsutils.appendPath(teamCfgDir, 'room.xls')
        jsonallfile = fsutils.appendPath(teamCfgDir, '0.json.all')
        jsonfile = fsutils.appendPath(teamCfgDir, 'room.json')
        jsonfileprev = fsutils.appendPath(teamCfgDir, 'room.json.prev')

        self._svnCmd(teamCfgDir, 'update', xlsfile)
        # 获取历史记录 svn log
        _, _, svnlog = self._svnCmd(teamCfgDir, 'log', '-l 5', xlsfile)
        logcontent = '\n'.join([
            line for line in svnlog.split('\n') if not line.startswith('-----')
        ])
        svnlog = svnlog.replace('\n', '<br/>')

        commands.getstatusoutput("rm -f [0-9]*.json")

        try:
            room_conf_generator.gen_split_file(xlsfile, teamCfgDir)
        except Exception, e:
            errstr = traceback.format_exc()
            mo = MsgPack()
            mo.setCmd('json_file_data')
            mo.setResult('isOk', False)
            mo.setResult("error", errstr)
            return mo

        commands.getstatusoutput("/bin/cp -f %s %s" % (jsonallfile, jsonfile))
        self._svnCmd(teamCfgDir, 'commit', jsonfile, '-m', '"%s"' % logcontent)
        self._svnCmd(teamCfgDir, 'export', '-rPREV', jsonfile, jsonfileprev,
                     '--force')

        #datas = fsutils.readJsonFile(jsonfile)
        mo = MsgPack()
        mo.setCmd('json_file_data')
        mo.setResult('isOk', True)
        mo.setResult('svn_commit_log', svnlog)
        mo.setResult('jsonfile', jsonfile)
        mo.setResult('jsonfileprev', jsonfileprev)
        return mo
Exemplo n.º 29
0
 def parseData(self, data):
     mpack = MsgPack()
     mpack.unpack(data)
     return mpack
Exemplo n.º 30
0
    def do_http_t3flush_precommit(self, branch):
        self._initBase()
        ftlog.debug("do_http_t3flush_precommit branch:", branch)
        if branch == 'testing':
            jsonfile = os.path.join(teamCfgDir, '0.json.all')
            jsonfileprev = os.path.join(testingDir, '0.json.all')
        elif branch == 'release':
            jsonfile = os.path.join(testingDir, '0.json.all')
            jsonfileprev = os.path.join(releaseDir, '0.json.all')

        _, _, svnlog = self._svnCmd(teamRoot, 'log', '-l 5', jsonfileprev)
        svnlog = '\n'.join([
            line for line in svnlog.split('\n')
            if not line.startswith('------')
        ])

        mo = MsgPack()
        mo.setCmd('t3flush_precommit')
        mo.setResult('isOk', True)
        mo.setResult('jsonfile', jsonfile)
        mo.setResult('jsonfileprev', jsonfileprev)
        mo.setResult('svnlog', svnlog)
        return mo
Exemplo n.º 31
0
 def jsonrsp(self, cmd, **result):
     msg = MsgPack()
     msg.setCmd(cmd)
     msg.setKey('result', result)
     return msg