예제 #1
0
파일: svn.py 프로젝트: zhaozw/hall37
def svnCmd(workingpath, cmd, *svnArgs):
    tylog.debug('svnCmd <<| workingpath, svnCmd, svnArgs:',
                workingpath, cmd, ' '.join(svnArgs))
    parts = []
    if workingpath:
        parts.append('cd %s' % workingpath)
    parts.append('LANG=en_US.UTF-8')
    parts.append(' '.join(['svn', cmd, '--non-interactive'] + list(svnArgs)))

    script = ';'.join(parts)
    status, output = commands.getstatusoutput(script)

    if status != 0:
        tylog.error("svnCmd >>| Failed"
                    '|path, cmd:', workingpath, cmd,
                    '|script:', script,
                    '|status, output:', status, output,
                    )
    else:
        tylog.debug('svnCmd >>'
                    '|path, cmd:', workingpath, cmd,
                    #'|script:', script,
                    #'|status, output:', status, output
                    )

    return script, status, output
예제 #2
0
    def doCommit(self, name, branch, log):
        configMod = self.configMods[name]
        if branch == 'testing':
            _file = configMod.testingFile
        elif branch == 'release':
            fsutils.copyFile(configMod.testingFile, configMod.releaseFile)
            _file = configMod.releaseFile
        else:
            tylog.error("doCommit| unknown branch"
                        "| gameId, name, branch:", self.gameId, name, branch)
            output = "\n错误: unknown branch: %s" % branch
            output = output.replace(' ', '&nbsp;').replace('\n', '<br />')

            return self.jsonrsp('commit', isOk=True, output=output)

        if svn.status(_file) == 'unversioned':
            svn.add(_file)

        output = svn.commit(_file, log)
        outputLines = [
            '',
            '提交文件到 %s:' % branch,
            './game/%s/%s/0.json' % (self.gameId, name),
            '',
            '修改内容:',
            log,
            '',
            '提交结果:',
            output,
        ]
        output = '\n'.join(outputLines)
        output = output.replace(' ', '&nbsp;').replace('\n', '<br />')

        return self.jsonrsp('commit', isOk=True, output=output)
예제 #3
0
    def doCommit(self, name, branch, log):
        configMod = self.configMods[name]
        if branch == 'testing':
            _file = configMod.testingFile
        elif branch == 'release':
            fsutils.copyFile(configMod.testingFile, configMod.releaseFile)
            _file = configMod.releaseFile
        else:
            tylog.error("doCommit| unknown branch"
                        "| gameId, name, branch:", self.gameId, name, branch)
            output = "\n错误: unknown branch: %s" % branch
            output = output.replace(' ', '&nbsp;').replace('\n', '<br />')

            return self.jsonrsp('commit', isOk=True, output=output)

        if svn.status(_file) == 'unversioned':
            svn.add(_file)

        output = svn.commit(_file, log)
        outputLines = [
            '',
            '提交文件到 %s:' % branch,
            './game/%s/%s/0.json' % (self.gameId, name),
            '',
            '修改内容:',
            log,
            '',
            '提交结果:',
            output,
        ]
        output = '\n'.join(outputLines)
        output = output.replace(' ', '&nbsp;').replace('\n', '<br />')

        return self.jsonrsp('commit', isOk=True, output=output)
예제 #4
0
def redis_do_command(options, userId, roomId, ralias, cmdline):

    datas = _getLastOkDefines(options)
    rdbs = datas['dbdict']['redis']
    if ralias == 'config':
        rdb = datas['pokerdict']['config_redis']
    elif ralias == 'user':
        if userId <= 0:
            return 'param userId ERROR !!'
        rdb = _getRedisDefCluster(rdbs, userId)
    elif ralias == 'table':
        if roomId <= 0:
            return 'param roomId ERROR !!'
        rdb = _getRedisDefCluster(rdbs, roomId, 'table')
    else:
        rdb = rdbs[ralias]

    conn = tydb.get_redis_conn(rdb)
    tylog.debug('redis_do_command->', cmdline)
    for x in xrange(len(cmdline)):
        c = cmdline[x]
        cmdline[x] = _decode_x(c)
    try:
        data = conn.execute_command(*cmdline)
    except Exception, ex:
        data = str(ex)
        tylog.error(cmdline)
예제 #5
0
파일: redisdata.py 프로젝트: zhaozw/hall37
def redis_do_command(options, userId, roomId, ralias, cmdline):
    
    datas = _getLastOkDefines(options)
    rdbs = datas['dbdict']['redis']
    if ralias == 'config' :
        rdb = datas['pokerdict']['config_redis']
    elif ralias == 'user' :
        if userId <= 0 :
            return 'param userId ERROR !!'
        rdb = _getRedisDefCluster(rdbs, userId)
    elif ralias == 'table' :
        if roomId <= 0 :
            return 'param roomId ERROR !!'
        rdb = _getRedisDefCluster(rdbs, roomId, 'table')
    else:
        rdb = rdbs[ralias]

    conn = tydb.get_redis_conn(rdb)
    tylog.debug('redis_do_command->', cmdline)
    for x in xrange(len(cmdline)) :
        c = cmdline[x]
        cmdline[x] = _decode_x(c)
    try:
        data = conn.execute_command(*cmdline)
    except Exception, ex:
        data = str(ex)
        tylog.error(cmdline)
예제 #6
0
 def do_http_confighttp(self, action, gameId, name):
     gameHandler = self.gameCfgHandlers[gameId]
     try:
         return gameHandler.onAction(action, name)
     except Exception:
         # TODO: error to page
         tylog.error('BaseActionHandler.do_http_config_http '
                     '|action, name, gameId:', action, name, gameId)
예제 #7
0
파일: runhttp.py 프로젝트: zhaozw/hall37
 def cbProxyBody(responsebody):
     try:
         request.write(responsebody)
     except:
         tylog.error('doProxy->cbProxyBody', httpurl)
     try:
         resultDeferred.callback('')
     except:
         tylog.error('doProxy->cbProxyBody', httpurl)
예제 #8
0
 def do_http_confighttp(self, action, gameId, name):
     gameHandler = self.gameCfgHandlers[gameId]
     try:
         return gameHandler.onAction(action, name)
     except Exception:
         # TODO: error to page
         tylog.error(
             'BaseActionHandler.do_http_config_http '
             '|action, name, gameId:', action, name, gameId)
예제 #9
0
파일: runhttp.py 프로젝트: zhaozw/hall37
 def cbProxyBody(responsebody):
     try:
         request.write(responsebody)
     except:
         tylog.error('doProxy->cbProxyBody', httpurl)
     try:
         resultDeferred.callback('')
     except:
         tylog.error('doProxy->cbProxyBody', httpurl)
예제 #10
0
파일: tytasklet.py 프로젝트: zhaozw/hall37
 def tasklet(self):
     self._return_channel = TYChannel()
     self._me = stackless.getcurrent()
     self._timeocall = None
     self._me._fttask = self
     try:
         self.handle()
     except:
         tylog.error('tasklet handle error')
     TyTasklet.concurrent_task_count -= 1
예제 #11
0
파일: runhttp.py 프로젝트: zhaozw/hall37
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)
예제 #12
0
    def doConvertOne(self, name):
        try:
            configMod = self.configMods.get(name)
            if configMod:
                jsonData = configMod.converter.convert(self)
                self.writeFile(configMod.testingFile, jsonData)
                modified = svn.status(configMod.testingFile) == 'modified'

                return self.jsonrsp('generate', isOk=True, modified=modified)
        except:
            tylog.error("doGenJson|name:", name)
예제 #13
0
    def doConvertOne(self, name):
        try:
            configMod = self.configMods.get(name)
            if configMod:
                jsonData = configMod.converter.convert(self)
                self.writeFile(configMod.testingFile, jsonData)
                modified = svn.status(configMod.testingFile) == 'modified'

                return self.jsonrsp('generate', isOk=True, modified=modified)
        except:
            tylog.error("doGenJson|name:", name)
예제 #14
0
파일: runhttp.py 프로젝트: zhaozw/hall37
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)
예제 #15
0
파일: tytasklet.py 프로젝트: zhaozw/hall37
 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
예제 #16
0
파일: tychannel.py 프로젝트: zhaozw/hall37
 def receive(self):
     try:
         if hasattr(self, 'value'):
             v = self.value
             del self.value
             return v
         if hasattr(self, 'exc'):
             ntype, value = self.exc
             del self.exc
             raise ntype, value
         return stackless.channel.receive(self)
     except:
         tylog.error("Channel receive error")
         return None
예제 #17
0
    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)
예제 #18
0
파일: runhttp.py 프로젝트: zhaozw/hall37
 def cbProxyRequest(response):
     try:
         request.setResponseCode(response.code)
         for k, v in response.headers.getAllRawHeaders():
             if isinstance(v, (list, tuple)) :
                 for vv in v :
                     request.setHeader(k, vv)
             else:
                 request.setHeader(k, v)
     except:
         tylog.error('doProxy->cbProxyRequest', httpurl)
     dd = readBody(response)
     dd.addCallback(cbProxyBody)
     return dd
예제 #19
0
파일: runhttp.py 프로젝트: zhaozw/hall37
 def cbProxyRequest(response):
     try:
         request.setResponseCode(response.code)
         for k, v in response.headers.getAllRawHeaders():
             if isinstance(v, (list, tuple)):
                 for vv in v:
                     request.setHeader(k, vv)
             else:
                 request.setHeader(k, v)
     except:
         tylog.error('doProxy->cbProxyRequest', httpurl)
     dd = readBody(response)
     dd.addCallback(cbProxyBody)
     return dd
예제 #20
0
파일: tychannel.py 프로젝트: zhaozw/hall37
 def receive(self):
     try:
         if hasattr(self, 'value'):
             v = self.value
             del self.value
             return v
         if hasattr(self, 'exc'):
             ntype, value = self.exc
             del self.exc
             raise ntype, value
         return stackless.channel.receive(self)
     except:
         tylog.error("Channel receive error")
         return None
예제 #21
0
    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)
예제 #22
0
파일: typrotocol.py 프로젝트: zhaozw/hall37
 def dataReceived(self, msg):
     if self.__handsake == 0 :
         try:
             self.handShake(msg)
         except:
             tylog.error()
             self.wsClose()
     else:
         try:
             self.__buffer = self.__buffer + msg
             if self.__is_new_ver:
                 self.parseRecvDataNew()
             else:
                 self.parseRecvDataOld()
         except:
             tylog.error()
예제 #23
0
 def dataReceived(self, msg):
     if self.__handsake == 0:
         try:
             self.handShake(msg)
         except:
             tylog.error()
             self.wsClose()
     else:
         try:
             self.__buffer = self.__buffer + msg
             if self.__is_new_ver:
                 self.parseRecvDataNew()
             else:
                 self.parseRecvDataOld()
         except:
             tylog.error()
예제 #24
0
파일: server.py 프로젝트: zhaozw/hall37
 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
예제 #25
0
파일: server.py 프로젝트: zhaozw/hall37
 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
예제 #26
0
파일: runhttp.py 프로젝트: zhaozw/hall37
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)
예제 #27
0
파일: runhttp.py 프로젝트: zhaozw/hall37
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)
예제 #28
0
파일: typrotocol.py 프로젝트: zhaozw/hall37
    def _runTasklet(self, *argl, **argd):
        try:
            # Call user defined parseData method...
            data = argd["data"]
            pack = self.parseData(data)
            if pack == None:
                tylog.error("_runTasklet: can't parseData received(%s....)" % data[0:64])
                return
            argd["pack"] = pack

            # Call user defined getTaskletFunc...
            taskf = self.getTaskletFunc(argd)
            if taskf == None:
                tylog.error("_runTasklet: can't find tasklet func by pack:(%r....)" % pack[0:64])
                return
            argd["handler"] = taskf

            # Create and run tasklet...
            TyTasklet.create(argl, argd)
        except:
            tylog.error()
예제 #29
0
    def _runTasklet(self, *argl, **argd):
        try:
            # Call user defined parseData method...
            data = argd["data"]
            pack = self.parseData(data)
            if pack == None:
                tylog.error("_runTasklet: can't parseData received(%s....)" %
                            data[0:64])
                return
            argd["pack"] = pack

            # Call user defined getTaskletFunc...
            taskf = self.getTaskletFunc(argd)
            if taskf == None:
                tylog.error(
                    "_runTasklet: can't find tasklet func by pack:(%r....)" %
                    pack[0:64])
                return
            argd["handler"] = taskf

            # Create and run tasklet...
            TyTasklet.create(argl, argd)
        except:
            tylog.error()
예제 #30
0
파일: tytasklet.py 프로젝트: zhaozw/hall37
 def _timeout(self, d):
     tylog.error("Tasklet.waitDefer timeout!!!", d)
     d.cancel()
예제 #31
0
파일: cron.py 프로젝트: zhaozw/hall37
    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
예제 #32
0
파일: cron.py 프로젝트: zhaozw/hall37
    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
예제 #33
0
파일: svn.py 프로젝트: zhaozw/hall37
# coding: utf-8

"""
对svn命令的包装
"""

import commands
import traceback
from tyserver.tyutils import tylog

try:
    from lxml import etree
except:
    tylog.error("import etree error")


def svnCmd(workingpath, cmd, *svnArgs):
    tylog.debug('svnCmd <<| workingpath, svnCmd, svnArgs:',
                workingpath, cmd, ' '.join(svnArgs))
    parts = []
    if workingpath:
        parts.append('cd %s' % workingpath)
    parts.append('LANG=en_US.UTF-8')
    parts.append(' '.join(['svn', cmd, '--non-interactive'] + list(svnArgs)))

    script = ';'.join(parts)
    status, output = commands.getstatusoutput(script)

    if status != 0:
        tylog.error("svnCmd >>| Failed"
                    '|path, cmd:', workingpath, cmd,
예제 #34
0
 def process(self):
     try:
         self._runTasklet(data=self.path, httprequest=self)
     except:
         tylog.error()
예제 #35
0
 def initGameHandler(self, gameId, cls):
     try:
         self.gameCfgHandlers[gameId] = cls(self.options, gameId)
     except Exception:
         tylog.error("BaseActionEntry.tryLoadGameHandler|gameId:", gameId)
예제 #36
0
파일: runws.py 프로젝트: zhaozw/hall37
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)
예제 #37
0
파일: runws.py 프로젝트: zhaozw/hall37
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)
예제 #38
0
파일: typrotocol.py 프로젝트: zhaozw/hall37
 def process(self):
     try:
         self._runTasklet(data=self.path, httprequest=self)
     except:
         tylog.error()
예제 #39
0
파일: actions.py 프로젝트: zhaozw/hall37
    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
예제 #40
0
 def initGameHandler(self, gameId, cls):
     try:
         self.gameCfgHandlers[gameId] = cls(self.options, gameId)
     except Exception:
         tylog.error("BaseActionEntry.tryLoadGameHandler|gameId:", gameId)