示例#1
0
文件: actions.py 项目: zhaozw/hall37
    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
示例#2
0
def remove_action(options, uuids) :
    fpath = options.logpath
    for uuid in uuids :
        fpath = fsutils.appendPath(options.logpath, 'action.' + uuid + '.json')
        fsutils.deleteFile(fpath)
        fpath = fsutils.appendPath(options.logpath, 'action.' + uuid + '.log')
        fsutils.deleteFile(fpath)
示例#3
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
示例#4
0
def action(options):
    '''
    load and check the poker file
    '''
    myenv = {'poker_path': options.poker_path}

    pokerdict = __load_poker_file(options)
    if not pokerdict:
        return 0
    __print_poker_info(options, pokerdict)
    setattr(options, 'pokerdict', pokerdict)

    # fix path of output
    outpath = pokerdict['output_path']
    pokerdict['bin_path'] = fsutils.appendPath(outpath, 'bin')
    pokerdict['webroot_path'] = fsutils.appendPath(outpath, 'webroot')
    pokerdict['backup_path'] = fsutils.appendPath(outpath, 'backup')

    for k, v in pokerdict.items():
        if isinstance(v, (str, unicode, int, float, bool)):
            myenv[str(k)] = v
        else:
            myenv[str(k)] = json.dumps(v)
    setattr(options, 'env', myenv)

    return 1
示例#5
0
def remove_action(options, uuids):
    fpath = options.logpath
    for uuid in uuids:
        fpath = fsutils.appendPath(options.logpath, 'action.' + uuid + '.json')
        fsutils.deleteFile(fpath)
        fpath = fsutils.appendPath(options.logpath, 'action.' + uuid + '.log')
        fsutils.deleteFile(fpath)
示例#6
0
def __load_project_file(options):
    jname = 'poker/project.json'
    datadict = __load_json_file(options, jname, list)

    if not datadict:
        return datadict

    game_packages = []
    gameids = []

    for proj in datadict:
        ppath = proj.get('path', None)
        if not isinstance(ppath, str):
            return actlog.error('the project path is not defined !', proj)
        if not fsutils.dirExists(ppath):
            return actlog.error('the project path not found !', ppath)

        srcpath = fsutils.appendPath(ppath, 'src')
        if fsutils.dirExists(srcpath):
            subdirs = os.listdir(srcpath)
            for subdir in subdirs:
                gamepy = fsutils.appendPath(srcpath, subdir, 'game.py')
                if fsutils.fileExists(gamepy):
                    if subdir in game_packages:
                        return actlog.error(
                            'the project package is double defined !', gamepy,
                            'proj=', proj)
                    game_packages.append(subdir)
                    proj['package'] = subdir
                    gameid = proj.get('gameId', 0)
                    if gameid > 0:
                        gameids.append(int(gameid))
                    actlog.log('find gam project-> GAMEID=', gameid,
                               'PACKAGE=', subdir)
    return datadict, game_packages, gameids
示例#7
0
def _thread_action_push_ssh(controls):
    
    controls['percent'] = '---%'
    
    params = controls['params']
    machine = controls['machine']
    tarfile = params['tarfile']
    taroutpath = params['taroutpath']
    tarsubpath = params['tarsubpath']
    rmLeft = params['rmLeft']
    options = params['options']
    tarpath = fsutils.getParentDir(tarfile)

    host = machine['host']
    tyssh.connect(host, machine['user'], machine['pwd'], machine['ssh'])
    
    controls['percent'] = '--+%'
    tyssh.mkdirs(host, options.env['output_path'])
    tyssh.mkdirs(host, options.env['log_path'])
    tyssh.mkdirs(host, options.env['webroot_path'])
    tyssh.mkdirs(host, options.env['bin_path'])
    tyssh.mkdirs(host, options.env['backup_path'])
    tyssh.mkdirs(host, tarpath)

    controls['percent'] = '000%'
    localfilesize = os.path.getsize(tarfile)

    def update_send_size(sendsize_, allsize_):
        if sendsize_ == allsize_ :
            p = 100
        else:
            p = int((float(sendsize_) / float(allsize_)) * 100)
        controls['percent'] = '% 3d' % (p) + '%'

    putsize = tyssh.put_file(host, tarfile, tarfile, update_send_size)
    if int(putsize) != localfilesize :
        return 2, 'SSH Push ERROR ' + tarfile

    controls['percent'] = '110%'
    
    bin_path = options.env['bin_path']
    remotepy = fsutils.appendPath(bin_path, 'remote.py')
    remotetarpy = fsutils.appendPath(tarpath, 'remote.py')
    putsize = tyssh.put_file(host, remotepy, remotetarpy, None)
    localfilesize = os.path.getsize(remotepy)
    if int(putsize) != localfilesize :
        return 2, 'SSH Push ERROR ' + remotetarpy

    controls['percent'] = '120%'
    cmdline = 'pypy %s %s %s %s %s %s' % (remotetarpy, 'xvf', tarfile, taroutpath, tarsubpath, rmLeft)
    outputs = tyssh.executecmd(host, cmdline)
    status = tyssh.parse_remote_datas_int(outputs)
    if status != 0 :
        for l in outputs.split('\n'):
            actlog.log('REMOTE ERROR', l)
        return 2, 'SSH Push remote tar xvf ERROR'

    controls['percent'] = '++++'
    return 1, ''
示例#8
0
文件: main.py 项目: zhaozw/hall37
def main():
    from optparse import OptionParser
    from tyserver.tyutils import fsutils
    
    parser = OptionParser(version="%prog 1.0", usage="%prog --path entrancepath --port Num")  
    parser.add_option("--path", dest="pokerpath", default=None,
                      help="must specified the service entrance path, the poker.json's path")  
    parser.add_option("--httpport", dest="httpport", default=None,
                      help="the http port")  

    options, _ = parser.parse_args()
    pokerpath = options.pokerpath
    if not pokerpath :
        print "must specified the service entrance path"
        parser.print_help()
        return None

    pokerpath = fsutils.makeAsbpath(options.pokerpath)
    if not fsutils.dirExists(pokerpath) :
        print "the service entrance path not exists [" + pokerpath + ']'
        parser.print_help()
        return None

    setattr(options, 'pokerpath', pokerpath)

    port = options.httpport
    try:
        port = int(options.httpport)
        setattr(options, 'httpport', port)
    except:
        print "the http port must be a integer"
        parser.print_help()
        return

    workpath = fsutils.getParentDir(__file__, 1)
    setattr(options, 'workpath', workpath)

    fpath = os.environ.get('LOGDIR', '')
    if not fpath :
        fpath = fsutils.appendPath(workpath, './../logs')
        fpath = fsutils.abspath(fpath)
        fsutils.makeDirs(fpath)
    setattr(options, 'logpath', fpath)

    print "pokerpath =", options.pokerpath
    print "httpport  =", options.httpport
    print "workpath  =", options.workpath

    flogfile = fsutils.appendPath(fpath, 'webmagr.log') 
    setattr(options, 'logfile', flogfile)

    from tyserver.server import startup
    from webmgr.manager import initialize, heartbeat
    setattr(options, 'initialize', initialize)
    setattr(options, 'heartbeat', heartbeat)
    startup(options)
示例#9
0
def save_action_history(options, action):
    actlistcond.acquire()
    try:
        fpath = fsutils.appendPath(options.logpath, 'action.' + action['uuid'] + '.json')
        fsutils.writeFile('', fpath, action)
    finally:
        actlistcond.release()
示例#10
0
文件: actions.py 项目: zhaozw/hall37
 def do_http_dizhu_room_list(self):
     ftlog.debug('do_http_dizhu_room_list')
     roomsPath = fsutils.appendPath(self.gameConfPath, 'room/0.json')
     with open(roomsPath, 'r') as f:
         rooms = json.load(f)
         return {'ec': 0, 'rooms': rooms}
     return {'ec': -1, 'info': 'Failed open file'}
示例#11
0
def makeSoInDocker(options):
    found = 0
    for proj in options.projectlist:
        srcPath = fsutils.appendPath(proj['path'], 'src')
        actlog.log('makeSoInDocker', srcPath)
        if platform.system() == 'Windows':
            _, makesosh = fsutils.findTreeFiles(
                srcPath, ['.*' + os.path.sep + '(makeso.cmd)$'],
                ['.*\\.svn.*'])
        else:
            _, makesosh = fsutils.findTreeFiles(
                srcPath, ['.*' + os.path.sep + '(makeso.sh)$'], ['.*\\.svn.*'])
        if makesosh:
            for msh in makesosh:
                found = 1
                cmd = srcPath + os.path.sep + msh
                os.chmod(cmd, stat.S_IRWXU | stat.S_IRWXG)
                actlog.log('run C/C++ compiler   :', msh)
                status, output = commands.getstatusoutput(cmd)
                if status != 0:
                    actlog.log('C/C++ compiler ERROR !!', cmd)
                    actlog.log(output)
                    return 0
    if not found:
        actlog.log('run C/C++ compiler   : not so found !!')
    return 1
示例#12
0
文件: actions.py 项目: zhaozw/hall37
 def do_http_dizhu_room_list(self):
     ftlog.debug('do_http_dizhu_room_list')
     roomsPath = fsutils.appendPath(self.gameConfPath, 'room/0.json')
     with open(roomsPath, 'r') as f:
         rooms = json.load(f)
         return {'ec':0, 'rooms':rooms}
     return {'ec':-1, 'info':'Failed open file'}
示例#13
0
def action(options):
    '''
    生成所有的进程启动脚本
    '''
    bin_path = options.env['bin_path']
    config_redis = options.pokerdict.get('local_config_redis',
                                         options.pokerdict['config_redis'])
    remotepy = loadResource('remote.py')
    remotepy = remotepy.replace('${TIME}', str(datetime.now()))
    remotepy = remotepy.replace('${BIN_PATH}', bin_path)
    remotepy = remotepy.replace('${LOG_PATH}', options.env['log_path'])
    remotepy = remotepy.replace('${REDIS_CONFIG}', config_redis)

    cfilepath = fsutils.appendPath(bin_path, 'remote.py')
    fsutils.writeFile('', cfilepath, remotepy)

    if options.pokerdict['mode'] <= 2:
        sendmail = '1'
    else:
        sendmail = '0'

    while1sh = loadResource('while1.sh')
    while1sh = while1sh.replace('${SENDMAIL}', sendmail)
    while1sh = while1sh.replace('${BIN_PATH}', bin_path)
    while1sh = while1sh.replace('${LOG_PATH}', options.env['log_path'])

    if os.environ.get('RUN_IN_DOCKER', 0):
        # 在开发docker模式下,设置PYTHONPATH环境变量
        paths = []
        for proj in options.projectlist:
            src = fsutils.appendPath(proj['path'], 'src')
            if fsutils.dirExists(src):
                paths.append(src)
            else:
                src = fsutils.appendPath(proj['path'], 'freetime')
                if fsutils.dirExists(src):
                    paths.append(proj['path'])
        paths.reverse()
        paths = ':'.join(paths)
        while1sh = while1sh.replace('${DOCKER_PROJECT_PATH}', paths)
        actlog.log('makeControlInDocker PYTHONPATH=', paths)

    shfile = fsutils.appendPath(bin_path, 'while1.sh')
    fsutils.writeFile('', shfile, while1sh)
    os.chmod(shfile, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)

    return 1
示例#14
0
def __load_json_file(options, jname, jtype):
    jsonfile = fsutils.appendPath(options.poker_path, jname)
    actlog.log('load %-15s :' % (jname), jsonfile)
    datadict = fsutils.readJsoFileParseEnv(options.env, jsonfile, True)
    if not isinstance(datadict, jtype):
        return actlog.error(jname + ' : format error, root object must be ' +
                            str(jtype))
    return datadict
示例#15
0
def action(options):
    '''
    生成所有的进程启动脚本
    '''
    bin_path = options.env['bin_path']
    config_redis = options.pokerdict.get('local_config_redis', options.pokerdict['config_redis'])
    remotepy = loadResource('remote.py')
    remotepy = remotepy.replace('${TIME}', str(datetime.now()))
    remotepy = remotepy.replace('${BIN_PATH}', bin_path)
    remotepy = remotepy.replace('${LOG_PATH}', options.env['log_path'])
    remotepy = remotepy.replace('${REDIS_CONFIG}', config_redis)

    cfilepath = fsutils.appendPath(bin_path, 'remote.py')
    fsutils.writeFile('', cfilepath, remotepy)

    if options.pokerdict['mode'] <= 2 :
        sendmail = '1'
    else:
        sendmail = '0'

    while1sh = loadResource('while1.sh')
    while1sh = while1sh.replace('${SENDMAIL}', sendmail)
    while1sh = while1sh.replace('${BIN_PATH}', bin_path)
    while1sh = while1sh.replace('${LOG_PATH}', options.env['log_path'])

    if os.environ.get('RUN_IN_DOCKER', 0):
        # 在开发docker模式下,设置PYTHONPATH环境变量
        paths = []
        for proj in options.projectlist:
            src = fsutils.appendPath(proj['path'], 'src')
            if fsutils.dirExists(src):
                paths.append(src)
            else:
                src = fsutils.appendPath(proj['path'], 'freetime')
                if fsutils.dirExists(src):
                    paths.append(proj['path'])
        paths.reverse()
        paths = ':'.join(paths)
        while1sh = while1sh.replace('${DOCKER_PROJECT_PATH}', paths)
        actlog.log('makeControlInDocker PYTHONPATH=', paths)

    shfile = fsutils.appendPath(bin_path, 'while1.sh')
    fsutils.writeFile('', shfile, while1sh)
    os.chmod(shfile, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)

    return 1
示例#16
0
def save_action_history(options, action):
    actlistcond.acquire()
    try:
        fpath = fsutils.appendPath(options.logpath,
                                   'action.' + action['uuid'] + '.json')
        fsutils.writeFile('', fpath, action)
    finally:
        actlistcond.release()
示例#17
0
文件: mode1.py 项目: zhaozw/hall37
def make_process_list(options, machinedict, gameids):
    jname = 'poker/process.json'
    jsonfile = fsutils.appendPath(options.poker_path, jname)
    actlog.log('load %-15s :' % (jname), jsonfile)
    processlist = fsutils.readJsonFile(jsonfile, True)
    if not isinstance(processlist, dict) :
        return actlog.error(jname + ' : format error, root object must be dict'), machinedict
    return processlist, machinedict
示例#18
0
文件: mode1.py 项目: zhaozw/hall37
def make_process_list(options, machinedict, gameids):
    jname = 'poker/process.json'
    jsonfile = fsutils.appendPath(options.poker_path, jname)
    actlog.log('load %-15s :' % (jname), jsonfile)
    processlist = fsutils.readJsonFile(jsonfile, True)
    if not isinstance(processlist, dict):
        return actlog.error(
            jname + ' : format error, root object must be dict'), machinedict
    return processlist, machinedict
示例#19
0
def open_act_log(options, action):
    global _logf
    close_act_log()
    logpath = options.logpath
    fpath = fsutils.appendPath(logpath, 'action.' + action['uuid'] + '.log')
    if 'DEBUG' in os.environ:
        _logf = None
    else:
        _logf = open(fpath, 'a')
    action['logfile'] = fpath
    pass
示例#20
0
文件: actions.py 项目: zhaozw/hall37
 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
示例#21
0
文件: manager.py 项目: zhaozw/hall37
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 ====')
示例#22
0
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 ====')
示例#23
0
文件: __init__.py 项目: zhaozw/hall37
def execute_remote_py(options, machine, paramlist):
    bin_path = options.env['bin_path']
    remotepy = fsutils.appendPath(bin_path, 'remote.py')
    cmdline = ['pypy', remotepy]
    cmdline.extend(paramlist)
    if machine.get('localhost', 0) == 1:
        outputs = tyssh.executecmd_local(cmdline)
    else:
        host = machine['host']
        tyssh.connect(host, machine['user'], machine['pwd'], machine['ssh'])
        outputs = tyssh.executecmd(host, ' '.join(cmdline))
        tyssh.close_ip(host)
    result = tyssh.parse_remote_datas_int(outputs)
    return result, outputs
示例#24
0
文件: __init__.py 项目: zhaozw/hall37
def execute_remote_py(options, machine, paramlist):
    bin_path = options.env['bin_path']
    remotepy = fsutils.appendPath(bin_path, 'remote.py')
    cmdline = ['pypy', remotepy]
    cmdline.extend(paramlist)
    if machine.get('localhost', 0) == 1:
        outputs = tyssh.executecmd_local(cmdline)
    else:
        host = machine['host']
        tyssh.connect(host, machine['user'], machine['pwd'], machine['ssh'])
        outputs = tyssh.executecmd(host, ' '.join(cmdline))
        tyssh.close_ip(host)
    result = tyssh.parse_remote_datas_int(outputs)
    return result, outputs
示例#25
0
def action(options):
    '''
    拷贝源代码工程的webroot到编译输出目录,按照配置文件的工程列表进行顺序覆盖拷贝
    '''
    actlog.log('copy webroot to bin/webroot')

    if os.environ.get('RUN_IN_DOCKER', 0):
        # 在开发docker模式下,webroot为link模式,无需拷贝
        actlog.log('docker mode skip this step !')
        return 1

    allpaths = [
        options.env['webroot_path'],
        options.env['backup_path'],
    ]
    for mp in allpaths:
        fsutils.makePath(mp, False)

    paths = []
    for proj in options.projectlist:
        src = fsutils.appendPath(proj['path'], 'webroot')
        if fsutils.dirExists(src):
            paths.append({
                'path': src,
                'include': [],
                'exclude': [".*\\.svn\\.*", ".*pyc"]
            })

    if options.pokerdict['mode'] in (1, 2):
        fsutils.copyTree(paths, options.env['webroot_path'], logfun=actlog.log)
        return 1

    # MODE 3, 4: 只链接, 并且只链接 tygame-webroot/webroot
    dstpath = options.env['webroot_path']
    for pathconf in paths:
        if 'tygame-webroot' in pathconf['path']:
            srcpath = pathconf['path']
            if os.path.islink(dstpath):
                if os.readlink(dstpath) == srcpath:  # 已经链接好了
                    actlog.log('already linked.', dstpath, '->', srcpath)
                    return 1
            fsutils.deletePath(dstpath)
            os.symlink(srcpath, dstpath)
            actlog.log('symlink created.', dstpath, '->', srcpath)
            return 1
    else:
        fsutils.copyTree(paths, options.env['webroot_path'], logfun=actlog.log)
    return 1
示例#26
0
def get_action_list(options) :
    fpath = options.logpath
    lfs = os.listdir(fpath)
    actlist = []
    for lf in lfs :
        if lf.startswith('action.') and lf.endswith('.json') :
            af = fsutils.appendPath(fpath, lf)
            action = fsutils.readJsonFile(af)
            actlist.append(action)
    actlist.sort(key=lambda x : x['uuid'])
    
    while len(actlist) > 10 :
        remove_action(options, [actlist[0]['uuid']])
        del actlist[0]

    return actlist
示例#27
0
def get_action_list(options):
    fpath = options.logpath
    lfs = os.listdir(fpath)
    actlist = []
    for lf in lfs:
        if lf.startswith('action.') and lf.endswith('.json'):
            af = fsutils.appendPath(fpath, lf)
            action = fsutils.readJsonFile(af)
            actlist.append(action)
    actlist.sort(key=lambda x: x['uuid'])

    while len(actlist) > 10:
        remove_action(options, [actlist[0]['uuid']])
        del actlist[0]

    return actlist
示例#28
0
def __load_server_file(options, machinedict, gameids):
    mode = options.env['mode']
    processlist, machinedict = modefactory[mode].make_process_list(
        options, machinedict, gameids)
    if not processlist:
        return processlist

    allrooms = {}
    # 装载房间的配置,用于获取房间进程ID和数量
    for gameId in gameids:
        jname = 'game/' + str(gameId) + '/room/0.json'
        jsonfile = fsutils.appendPath(options.poker_path, jname)
        if fsutils.fileExists(jsonfile):
            actlog.log('load %-15s :' % (jname), jsonfile)
            rooms = fsutils.readJsonFile(jsonfile, True)
            if not isinstance(rooms, dict):
                return actlog.error(
                    jname + ' : format error, root object must be dict')
            for rid in rooms:
                if rid in allrooms:
                    return actlog.error(jname +
                                        ' : the roomId already defined !! ' +
                                        str(rid))
                allrooms[rid] = rooms[rid]

    serverlist = auto_process.auto_group_process(machinedict, processlist,
                                                 allrooms, mode)

    serverlist = strutil.replace_objevn_value(serverlist, options.env)

    checks = strutil.cloneData(serverlist)
    for _, m in options.machinedict.items():
        internet = m['internet']
        intranet = m['intranet']
        for x in xrange(len(checks) - 1, -1, -1):
            p = checks[x]
            if p['ip'] == internet or p['ip'] == intranet:
                del checks[x]

    if len(checks) > 0:
        for p in checks:
            actlog.error('can not find machine define of server ip :', p['ip'])
        return 0
    return serverlist
示例#29
0
def action(options):
    """
    拷贝源代码工程的etc、src、src-robot、webroot到编译输出目录,按照配置文件的工程列表进行顺序覆盖拷贝
    """
    # 创建所有的路径
    allpaths = [
        options.env['log_path'],
        options.env['webroot_path'],
        options.env['backup_path'],
    ]
    for mp in allpaths:
        fsutils.makePath(mp, False)
    allpaths = [
        options.env['bin_path']
    ]
    for mp in allpaths:
        fsutils.makePath(mp, True)

    if os.environ.get('RUN_IN_DOCKER', 0):
        # 在开发docker模式下,webroot为link模式,无需拷贝
        copySourceInDocker(options)
        actlog.log('docker mode use original project src path !')
        return 1

    paths = []
    for proj in options.projectlist:
        src = fsutils.appendPath(proj['path'], 'src')
        if fsutils.dirExists(src):
            paths.append({'path': src, 'include': [], 'exclude': [".*\\.svn\\.*", ".*pyc"]})
        else:  # freetime project
            paths.append({'path': proj['path'],
                          "include": ["^/freetime/.*"],
                          "exclude": [".*\\.svn\\.*",
                                      ".*pyc",
                                      ".*\\logserver\\.*",
                                      ".*\\cold-data-server\\.*"]})

    if ide_debug():
        _, copy_files = fsutils.linkTree(paths, options.env['bin_path'], logfun=actlog.log)
    else:
        _, copy_files = fsutils.copyTree(paths, options.env['bin_path'], logfun=actlog.log)
    setattr(options, '_pyfiles', copy_files)

    return 1
示例#30
0
def action(options):
    '''
    拷贝源代码工程的webroot到编译输出目录,按照配置文件的工程列表进行顺序覆盖拷贝
    '''
    actlog.log('copy webroot to bin/webroot')

    if os.environ.get('RUN_IN_DOCKER', 0) :
        # 在开发docker模式下,webroot为link模式,无需拷贝
        actlog.log('docker mode skip this step !')
        return 1

    allpaths = [
                options.env['webroot_path'],
                options.env['backup_path'],
    ]
    for mp in allpaths:
        fsutils.makePath(mp, False)

    paths = []
    for proj in options.projectlist :
        src = fsutils.appendPath(proj['path'], 'webroot')
        if fsutils.dirExists(src) :
            paths.append({'path':src, 'include' : [], 'exclude' : [".*\\.svn\\.*", ".*pyc"]})

    if options.pokerdict['mode'] in (1, 2):
        fsutils.copyTree(paths, options.env['webroot_path'], logfun=actlog.log)
        return 1

    # MODE 3, 4: 只链接, 并且只链接 tygame-webroot/webroot
    dstpath = options.env['webroot_path']
    for pathconf in paths:
        if 'tygame-webroot' in pathconf['path']:
            srcpath = pathconf['path']
            if os.path.islink(dstpath):
                if os.readlink(dstpath) == srcpath:  # 已经链接好了
                    actlog.log('already linked.', dstpath, '->', srcpath)
                    return 1
            fsutils.deletePath(dstpath)
            os.symlink(srcpath, dstpath)
            actlog.log('symlink created.', dstpath, '->', srcpath)
            return 1
    else:
        fsutils.copyTree(paths, options.env['webroot_path'], logfun=actlog.log)
    return 1
示例#31
0
def action(options):
    actlog.log('push static config file to all machines !')

    if os.environ.get('RUN_IN_DOCKER', 0):
        # 在开发docker模式下,webroot为link模式,无需拷贝
        actlog.log('docker mode skip this step !')
        return 1

    cpath = 'stc_' + datetime.now().strftime('%Y%m%d_%H%M%S')
    bpath = options.env['backup_path']
    outpath = fsutils.appendPath(bpath, cpath)
    stpath = options.env['webroot_path'] + '/static_file'
    tarfile = tytar.tar_cvfz(outpath, stpath)
    actlog.log('static config file =', tarfile)
    ret = typush.push_tar_to_all_server(options, tarfile,
                                        fsutils.getParentDir(stpath),
                                        fsutils.getLastPathName(stpath), 1)
    actlog.log('push static config file to all machines ! done !!')
    return ret
示例#32
0
文件: actions.py 项目: zhaozw/hall37
    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
示例#33
0
文件: actions.py 项目: zhaozw/hall37
 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
示例#34
0
    def calcAllStartTimes(self, days):
        '''
        获取所有比赛的所有场次的所有开赛时间

        return: {
            'mtt_chip_10w': {
                'name': '10万金币赛',
                'rooms': {
                    '8300': [
                        14232423423,
                        14232423423,
                        ...
                    ],
                    '8301': [
                        14232423423,
                        14232423423,
                        ...
                    ]
                }
            },
            'mtt_chip_100w': {...},
            ...
        }
        '''
        self._initBase()
        jsonfile = fsutils.appendPath(teamCfgDir, 'room.json')
        matchRoomConfs = fsutils.readJsonFile(jsonfile)

        allStartTimes = {}

        for roomId, roomConf in matchRoomConfs.items():
            if roomConf['typeName'] == 'mtt':
                matchConf = roomConf['matchConf']
                matchTypeId = matchConf['match_id']
                statTimeList = self.calcStartTimes(roomId, matchConf, days)
                if matchTypeId not in allStartTimes:
                    allStartTimes[matchTypeId] = {}
                    allStartTimes[matchTypeId]['name'] = roomConf['name']
                    allStartTimes[matchTypeId]['visible'] = matchConf[
                        'visible']
                    allStartTimes[matchTypeId]['rooms'] = {}
                allStartTimes[matchTypeId]['rooms'][roomId] = statTimeList
        return allStartTimes
示例#35
0
文件: actions.py 项目: zhaozw/hall37
    def calcAllStartTimes(self, days):
        '''
        获取所有比赛的所有场次的所有开赛时间

        return: {
            'mtt_chip_10w': {
                'name': '10万金币赛',
                'rooms': {
                    '8300': [
                        14232423423,
                        14232423423,
                        ...
                    ],
                    '8301': [
                        14232423423,
                        14232423423,
                        ...
                    ]
                }
            },
            'mtt_chip_100w': {...},
            ...
        }
        '''
        self._initBase()
        jsonfile = fsutils.appendPath(teamCfgDir, 'room.json')
        matchRoomConfs = fsutils.readJsonFile(jsonfile)

        allStartTimes = {}

        for roomId, roomConf in matchRoomConfs.items():
            if roomConf['typeName'] == 'mtt':
                matchConf = roomConf['matchConf']
                matchTypeId = matchConf['match_id']
                statTimeList = self.calcStartTimes(roomId, matchConf, days)
                if matchTypeId not in allStartTimes:
                    allStartTimes[matchTypeId] = {}
                    allStartTimes[matchTypeId]['name'] = roomConf['name']
                    allStartTimes[matchTypeId]['visible'] = matchConf['visible']
                    allStartTimes[matchTypeId]['rooms'] = {}
                allStartTimes[matchTypeId]['rooms'][roomId] = statTimeList
        return allStartTimes
示例#36
0
def action(options):
    actlog.log('push static config file to all machines !')

    if os.environ.get('RUN_IN_DOCKER', 0):
        # 在开发docker模式下,webroot为link模式,无需拷贝
        actlog.log('docker mode skip this step !')
        return 1

    cpath = 'stc_' + datetime.now().strftime('%Y%m%d_%H%M%S')
    bpath = options.env['backup_path']
    outpath = fsutils.appendPath(bpath, cpath)
    stpath = options.env['webroot_path'] + '/static_file'
    tarfile = tytar.tar_cvfz(outpath, stpath)
    actlog.log('static config file =', tarfile)
    ret = typush.push_tar_to_all_server(options, tarfile,
                                        fsutils.getParentDir(stpath),
                                        fsutils.getLastPathName(stpath),
                                        1)
    actlog.log('push static config file to all machines ! done !!')
    return ret
示例#37
0
def action(options):
    actlog.log('push webroot file to all machines !')

    if os.environ.get('RUN_IN_DOCKER', 0):
        # 在开发docker模式下,webroot为link模式,无需拷贝
        actlog.log('docker mode skip this step !')
        return 1

    if options.pokerdict['mode'] in (3, 4):
        actlog.log('Testing Mode, skip this step.')
        return 1
    cpath = 'web_' + datetime.now().strftime('%Y%m%d_%H%M%S')
    bpath = options.env['backup_path']
    outpath = fsutils.appendPath(bpath, cpath)
    webpath = options.env['webroot_path']
    tarfile = tytar.tar_cvfz(outpath, webpath)
    actlog.log('webroot file =', tarfile)
    ret = typush.push_tar_to_all_server(options, tarfile,
                                        fsutils.getParentDir(webpath),
                                        fsutils.getLastPathName(webpath), 0)
    actlog.log('push webroot file to all machines ! done !!')
    return ret
示例#38
0
文件: push_bin.py 项目: zhaozw/hall37
def action(options):
    actlog.log('push bin file to all machines !')

    if os.environ.get('RUN_IN_DOCKER', 0):
        # 在开发docker模式下,webroot为link模式,无需拷贝
        actlog.log('docker mode skip this step !')
        return 1

    if options.pokerdict['mode'] in (3, 4):
        actlog.log('Testing Mode, skip this step.')
        return 1
    cpath = 'bin_' + datetime.now().strftime('%Y%m%d_%H%M%S')
    bpath = options.env['backup_path']
    outpath = fsutils.appendPath(bpath, cpath)
    bin_path = options.env['bin_path']
    tarfile = tytar.tar_cvfz(outpath, options.env['bin_path'])
    actlog.log('bin file =', tarfile)
    ret = typush.push_tar_to_all_server(options, tarfile,
                                        fsutils.getParentDir(bin_path),
                                        fsutils.getLastPathName(bin_path),
                                        1)
    actlog.log('push bin file to all machines ! done !!')
    return ret
示例#39
0
def makeSoInDocker(options):
    found = 0
    for proj in options.projectlist:
        srcPath = fsutils.appendPath(proj['path'], 'src')
        actlog.log('makeSoInDocker', srcPath)
        if platform.system() == 'Windows':
            _, makesosh = fsutils.findTreeFiles(srcPath, ['.*' + os.path.sep + '(makeso.cmd)$'], ['.*\\.svn.*'])
        else:
            _, makesosh = fsutils.findTreeFiles(srcPath, ['.*' + os.path.sep + '(makeso.sh)$'], ['.*\\.svn.*'])
        if makesosh:
            for msh in makesosh:
                found = 1
                cmd = srcPath + os.path.sep + msh
                os.chmod(cmd, stat.S_IRWXU | stat.S_IRWXG)
                actlog.log('run C/C++ compiler   :', msh)
                status, output = commands.getstatusoutput(cmd)
                if status != 0:
                    actlog.log('C/C++ compiler ERROR !!', cmd)
                    actlog.log(output)
                    return 0
    if not found:
        actlog.log('run C/C++ compiler   : not so found !!')
    return 1
示例#40
0
def get_action_log(options, action_uuid, line_num):
    logpath = options.logpath
    fpath = fsutils.appendPath(logpath, 'action.' + action_uuid + '.log')
    lines = [] 
    if fsutils.fileExists(fpath) :
        f = None
        try:
            f = open(fpath)
            if line_num > 0 :
                for _ in xrange(line_num) :
                    f.readline()
            l = f.readline() 
            while l :
                lines.append(l.strip())
                l = f.readline()
        finally:
            try:
                f.close()
            except:
                pass
    else:
        lines.append('the log file is missing !!')
        lines.append(fpath)
    return lines
示例#41
0
def get_action_log(options, action_uuid, line_num):
    logpath = options.logpath
    fpath = fsutils.appendPath(logpath, 'action.' + action_uuid + '.log')
    lines = []
    if fsutils.fileExists(fpath):
        f = None
        try:
            f = open(fpath)
            if line_num > 0:
                for _ in xrange(line_num):
                    f.readline()
            l = f.readline()
            while l:
                lines.append(l.strip())
                l = f.readline()
        finally:
            try:
                f.close()
            except:
                pass
    else:
        lines.append('the log file is missing !!')
        lines.append(fpath)
    return lines
示例#42
0
def action(options):
    '''
    装载并检测服务启动配置文件
    '''
    alldata = {}
    setattr(options, 'alldata', alldata)

    actlog.log('options.poker_path->', options.poker_path)
    checkprojects = options.checkprojects
    loadsprojs = set()
    datas, allGameIds = load_project_datas_all(options.poker_path + '/game/', options)
    alldata.update(datas)
    for cproj in checkprojects:
        projectdir = fsutils.appendPath(options.poker_path, cproj)
        loadsprojs.add(projectdir)
        datas = load_project_datas_room(projectdir, options)
        alldata.update(datas)
    allGameIds.sort()
    options.pokerdict['config.game.ids'] = allGameIds
    actlog.log('config.game.ids->', allGameIds)
    alldata['poker:map.activityid'] = readJsonData(options.poker_path + '/poker/map.activityid.json', options)
    alldata['poker:map.bieventid'] = readJsonData(options.poker_path + '/poker/map.bieventid.json', options)
    alldata['poker:map.giftid'] = readJsonData(options.poker_path + '/poker/map.giftid.json', options)

    # 重gdss获取数据
    ret = _syncDataFromGdss(options, 'poker:map.clientid', dict, 'getClientIdDict')
    if not ret:
        return ret

    ret = _syncDataFromGdss(options, 'poker:map.productid', dict, 'getProductIdDict')
    if not ret:
        return ret

    ret = make_static_json.make_static_json_file(options, alldata)
    if not ret:
        return ret

    outpath = options.pokerdict['output_path']
    fsutils.writeFile(outpath, 'out.redis.json', alldata)
    fsutils.writeFile(outpath, 'out.poker.global.json', options.pokerdict)
    fsutils.writeFile(options.poker_path, '._confdata_.json', alldata)

    patchpy = os.path.dirname(outpath) + '/patch_config.py'
    if os.path.isfile(patchpy):
        cmd = 'pypy ' + patchpy + ' ' + outpath
        actlog.log('执行游戏配置文件补丁:', cmd)
        status, output = commands.getstatusoutput(cmd)
        for l in output.split('\n'):
            actlog.log(l)
        if status != 0:
            actlog.error('游戏配置文件补丁失败:', patchpy)
            actlog.error(status, output)
            return 0
        if output and output.find('REMAKE_STATIC') >= 0:
            actlog.log('find REMAKE_STATIC !')
            alldata = json.loads(filterComment(outpath + '/out.redis.json'))
            ret = make_static_json.make_static_json_file(options, alldata)
            if not ret:
                return ret
            fsutils.writeFile(outpath, 'out.redis.json', alldata)
            fsutils.writeFile(options.poker_path, '._confdata_.json', alldata)
    return 1
示例#43
0
def action(options):
    '''
    装载并检测服务启动配置文件
    '''
    projectlist, game_packages, gameids = __load_project_file(options)
    if not projectlist:
        return 0
    setattr(options, 'projectlist', projectlist)
    options.pokerdict['game_packages'] = game_packages

    otherconf = os.listdir(fsutils.appendPath(options.poker_path, 'game'))
    conf_projects = []
    for oc in otherconf:
        try:
            gid = int(oc)
            if gid in gameids:
                conf_projects.append('game/' + str(gid))
        except:
            pass
    if 'game/9998' not in conf_projects:
        conf_projects.append('game/9998')
    options.pokerdict['conf.projects'] = conf_projects
    #     actlog.log('projectlist=', projectlist)

    machinedict = __load_machine_file(options)
    if not machinedict:
        return 0
    setattr(options, 'machinedict', machinedict)

    myenv = options.env
    for mid, mdefs in machinedict.items():
        myenv[mid + '.internet'] = mdefs['internet']
        myenv[mid + '.intranet'] = mdefs['intranet']
    #     actlog.log('machinedict=', machinedict)

    globaldict = __load_global_file(options)
    if not globaldict:
        return 0
    setattr(options, 'globaldict', globaldict)
    #     actlog.log('globaldict=', globaldict)

    options.pokerdict['log_path'] = globaldict['log_path']
    myenv['log_path'] = globaldict['log_path']

    dbdict = __load_db_file(options)
    if not dbdict:
        return 0
    setattr(options, 'dbdict', dbdict)
    #     actlog.log('dbdict=', dbdict)

    myenv['db.mysql.all'] = dbdict['mysql'].keys()
    myenv['db.redis.all'] = dbdict['redis'].keys()

    serverlist = __load_server_file(options, machinedict, gameids)
    if not serverlist:
        return 0
    setattr(options, 'serverlist', serverlist)
    #     actlog.log('serverlist=', serverlist)

    cmddict = __load_cmd_file(options)
    if not cmddict:
        return 0
    setattr(options, 'cmddict', cmddict)
    #     actlog.log('cmddict=', cmddict)

    #     rooms = __load_rooms_file(options)
    #     if not rooms :
    #         return 0
    #     setattr(options, 'rooms', rooms)
    #     actlog.log('cmddict=', cmddict)

    datas = {}
    datas['env'] = options.env
    datas['pokerdict'] = options.pokerdict
    datas['projectlist'] = options.projectlist
    datas['machinedict'] = options.machinedict
    datas['globaldict'] = options.globaldict
    datas['dbdict'] = options.dbdict
    datas['serverlist'] = options.serverlist
    datas['cmddict'] = options.cmddict

    fsutils.writeFile(options.poker_path, '._service_.json', datas)
    fsutils.writeFile(options.poker_path, '._process_.json',
                      datas['serverlist'])
    fsutils.writeFile(options.poker_path, '._confprojects_.json',
                      conf_projects)

    outpath = options.pokerdict['output_path']
    fsutils.writeFile(outpath, 'out.datas.json', datas)
    fsutils.writeFile(outpath, 'out.db.json', datas['dbdict'])
    fsutils.writeFile(outpath, 'out.poker.global.json', datas['pokerdict'])
    fsutils.writeFile(outpath, 'out.freetime.global.json', datas['globaldict'])
    fsutils.writeFile(outpath, 'out.server.json', datas['serverlist'])

    if fsutils.fileExists(outpath + '/out.server.json.base'):
        s1 = fsutils.readFile(outpath + '/out.server.json.base')
        s2 = fsutils.readFile(outpath + '/out.server.json')
        if s1.strip() != s2.strip():
            raise Exception('the server.ison changed !! can not go !!')

    slist = []
    for k in datas['serverlist']:
        slist.append(
            str(k['type']) + str(k['id']) + ' ' +
            str(k['ip'] + ' ' + str(k.get('agent', ''))))
    slist.sort()
    slist = '\n'.join(slist)
    fsutils.writeFile(outpath, 'out.process.list', slist)

    return 1
示例#44
0
def copySourceInDocker(options):
    for proj in options.projectlist:
        runpy = fsutils.appendPath(proj['path'], 'src/run.py')
        if fsutils.fileExists(runpy):
            fsutils.copyFile(runpy, options.env['bin_path'] + '/run.py')
示例#45
0
文件: actions.py 项目: zhaozw/hall37
 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)
示例#46
0
def thread_do_action(options_, action):
    options = Values()
    setattr(options, 'poker_path', options_.pokerpath)
    setattr(options, 'pokerfile', fsutils.appendPath(options_.pokerpath, 'poker/global.json'))

    params = action['params']
    actname = action['action']

    if actname == 'config_check':
        thread_do_action_config(options, params)
        return

    if actname == 'config_reload':
        ret = thread_do_action_config(options, params)
        if ret:
            update_config.action(options)
        return

    if actname == 'config_update':
        setattr(options, 'reset', params.get('reset', 0))
        ret = thread_do_action_config(options, params)
        if ret:
            ret = update_config.action(options)
            if options.push_static:
                push_static.action(options)
            if ret:
                notify_config_change.action(options, params.get('keys', []))
        return

    if actname in ('config_compile_start', 'prepare'):
        ret = thread_do_action_config(options, params)
        if ret:
            if not update_config.action(options):
                return
    else:
        if not thread_do_action_config_base(options, params):
            return

    processids = params.get('processids', [])
    setattr(options, 'processids', processids)

    if actname == 'config_status':
        config_status.action(options)
        return

    if actname == 'config_process':
        pass

    if actname == 'compile_source':
        if not copy_source.action(options):
            return
        if not copy_webroot.action(options):
            return
        if not make_compile.action(options):
            return
        if not make_control.action(options):
            return
        return

    if actname == 'prepare':
        if not make_clean.action(options):
            return
        if not copy_source.action(options):
            return
        if not copy_webroot.action(options):
            return
        if not make_compile.action(options):
            return
        if not make_control.action(options):
            return
        if not push_webroot.action(options):
            return
        return

    if actname == 'config_compile_start':
        if not make_clean.action(options):
            return
        if not copy_source.action(options):
            return
        if not copy_webroot.action(options):
            return
        if not make_compile.action(options):
            return
        if not make_control.action(options):
            return
        if not push_bin.action(options):
            return
        if not stopall.action(options):
            return
        if not start.action(options):
            return
        if not push_webroot.action(options):
            return
        return

    if actname == 'reset':
        if not start.action(options):
            return
        return

    if actname == 'push_bin':
        if not push_bin.action(options):
            return
        return

    if actname == 'push_web':
        if not push_webroot.action(options):
            return
        return

    if actname == 'push_source':
        if not push_bin.action(options):
            return
        if not push_webroot.action(options):
            return
        return

    if actname == 'stop_all_process':
        if not stopall.action(options):
            return
        return

    if actname == 'svn_update_all':
        if not svnup.action(options, params):
            return
        return

    if actname == 'svn_update_config':
        if not svnupConfig.action(options, params):
            return
        return

    if actname == 'restart_mgr_thread':
        if not mgrthread.action(options):
            return
        return

    if actname == 'remove_all_logs':
        if not removelogs.action(options):
            return
        return
示例#47
0
文件: game.py 项目: zhaozw/hall37
def main():
    from tyserver.tyutils import fsutils
    actlog._with_std = 1

    options = parse_cmd_lines()
    if not hasattr(options, 'pokerpath') :
        useage()
        actlog.log('You must input -m <poker path>')
        return
    if not hasattr(options, 'action') :
        useage()
        actlog.log('You Must input -a <action>')
        return

    pokerpath = options.pokerpath
    if not pokerpath :
        actlog.log("must specified the service entrance path")
        useage()
        return None

    pokerpath = fsutils.makeAsbpath(options.pokerpath)
    if not fsutils.dirExists(pokerpath) :
        actlog.log("the service entrance path not exists [" + pokerpath + ']')
        useage()
        return None

    setattr(options, 'pokerpath', pokerpath)

    workpath = fsutils.getParentDir(__file__, 1)
    setattr(options, 'workpath', workpath)

    fpath = os.environ.get('LOGDIR', '')
    if fpath and fsutils.dirExists(fpath):
        fpath = fsutils.abspath(fpath)
        setattr(options, 'logpath', fpath)
        ct = datetime.now().strftime('%Y%m%d%H%M%S')
        actlog.open_act_log(options, {'uuid':ct})
    else:
        setattr(options, 'logpath', None)

    actlog.log("pokerpath =", options.pokerpath)
    actlog.log("workpath  =", options.workpath)
    actlog.log("logpath   =", options.logpath)

    flogfile = fsutils.appendPath(fpath, 'webmagr.log') 
    setattr(options, 'logfile', flogfile)
    
    actlog.log("action    =", options.action)
    if options.action == 'config_check' :
        action = {'action' : 'config_check',
                  'params':{}}
        thread_do_action(options, action)
        return

    if options.action == 'config_reload' :
        action = {'action' : 'config_reload',
                  'params':{}}
        thread_do_action(options, action)
        return

    if options.action == 'config_update' :
        keys = []
        if hasattr(options, 'keys') :
            keys =  options.keys.split(',')
        action = {'action' : 'config_update',
                  'params':{'keys' : keys}}
        thread_do_action(options, action)
        return

    if options.action == 'config_reset' :
        action = {'action' : 'config_update',
                  'params':{'reset' : 1}}
        thread_do_action(options, action)
        return

    if options.action == 'config_status' :
        action = {'action' : 'config_status',
                  'params':{}}
        thread_do_action(options, action)
        return
    
    if options.action == 'compile' :
        action = {'action' : 'compile_source',
                  'params':{}}
        thread_do_action(options, action)
        return

    if options.action == 'start' :
        action = {'action' : 'config_compile_start',
                  'params':{}}
        thread_do_action(options, action)
        return

    if options.action == 'reset' :
        if not hasattr(options, 'serverIds') :
            useage()
            actlog.log('You must input -sid XXX,XXX')
            return
        processids = options.serverIds.split(',')
        if not processids :
            useage()
            actlog.log('You must input -sid XXX,XXX')
            return
        action = {'action' : 'reset',
                  'params':{'processids' : processids}}
        thread_do_action(options, action)
        return
    
    if options.action == 'stop' :
        action = {'action' : 'stop_all_process',
                  'params':{}}
        thread_do_action(options, action)
        return
    
    if options.action == 'push_code' :
        action = {'action' : 'push_bin',
                  'params':{}}
        thread_do_action(options, action)
        return

    if options.action == 'push_web' :
        action = {'action' : 'push_web',
                  'params':{}}
        thread_do_action(options, action)
        return

    hotfixwait = 1
    if options.action == 'hotfix_nowait' :
        options.action = 'hotfix'
        hotfixwait = 0
    setattr(options, 'hotfixwait', hotfixwait)
        
    if options.action == 'hotfix' :
        if not hasattr(options, 'serverIds') :
            useage()
            actlog.log('You must input -sid XXX,XXX or -sid all')
            return
        if not hasattr(options, 'hotfixpy') :
            useage()
            actlog.log('You Must input -py xxxx.py')
            return
        hotfix.action(options)
        return

    if options.action == 'rm_logs' :
        action = {'action' : 'remove_all_logs',
                  'params':{}}
        thread_do_action(options, action)
        return

    actlog.log('unknow action of :', options.action)
    useage()
示例#48
0
def action(options):
    '''
    装载并检测服务启动配置文件
    '''
    alldata = {}
    setattr(options, 'alldata', alldata)

    actlog.log('options.poker_path->', options.poker_path)
    checkprojects = options.checkprojects
    loadsprojs = set()
    datas, allGameIds = load_project_datas_all(options.poker_path + '/game/',
                                               options)
    alldata.update(datas)
    for cproj in checkprojects:
        projectdir = fsutils.appendPath(options.poker_path, cproj)
        loadsprojs.add(projectdir)
        datas = load_project_datas_room(projectdir, options)
        alldata.update(datas)
    allGameIds.sort()
    options.pokerdict['config.game.ids'] = allGameIds
    actlog.log('config.game.ids->', allGameIds)
    alldata['poker:map.activityid'] = readJsonData(
        options.poker_path + '/poker/map.activityid.json', options)
    alldata['poker:map.bieventid'] = readJsonData(
        options.poker_path + '/poker/map.bieventid.json', options)
    alldata['poker:map.giftid'] = readJsonData(
        options.poker_path + '/poker/map.giftid.json', options)

    # 重gdss获取数据
    ret = _syncDataFromGdss(options, 'poker:map.clientid', dict,
                            'getClientIdDict')
    if not ret:
        return ret

    ret = _syncDataFromGdss(options, 'poker:map.productid', dict,
                            'getProductIdDict')
    if not ret:
        return ret

    ret = make_static_json.make_static_json_file(options, alldata)
    if not ret:
        return ret

    outpath = options.pokerdict['output_path']
    fsutils.writeFile(outpath, 'out.redis.json', alldata)
    fsutils.writeFile(outpath, 'out.poker.global.json', options.pokerdict)
    fsutils.writeFile(options.poker_path, '._confdata_.json', alldata)

    patchpy = os.path.dirname(outpath) + '/patch_config.py'
    if os.path.isfile(patchpy):
        cmd = 'pypy ' + patchpy + ' ' + outpath
        actlog.log('执行游戏配置文件补丁:', cmd)
        status, output = commands.getstatusoutput(cmd)
        for l in output.split('\n'):
            actlog.log(l)
        if status != 0:
            actlog.error('游戏配置文件补丁失败:', patchpy)
            actlog.error(status, output)
            return 0
        if output and output.find('REMAKE_STATIC') >= 0:
            actlog.log('find REMAKE_STATIC !')
            alldata = json.loads(filterComment(outpath + '/out.redis.json'))
            ret = make_static_json.make_static_json_file(options, alldata)
            if not ret:
                return ret
            fsutils.writeFile(outpath, 'out.redis.json', alldata)
            fsutils.writeFile(options.poker_path, '._confdata_.json', alldata)
    return 1
示例#49
0
文件: game.py 项目: zhaozw/hall37
def main():
    from tyserver.tyutils import fsutils
    actlog._with_std = 1

    options = parse_cmd_lines()
    if not hasattr(options, 'pokerpath'):
        useage()
        actlog.log('You must input -m <poker path>')
        return
    if not hasattr(options, 'action'):
        useage()
        actlog.log('You Must input -a <action>')
        return

    pokerpath = options.pokerpath
    if not pokerpath:
        actlog.log("must specified the service entrance path")
        useage()
        return None

    pokerpath = fsutils.makeAsbpath(options.pokerpath)
    if not fsutils.dirExists(pokerpath):
        actlog.log("the service entrance path not exists [" + pokerpath + ']')
        useage()
        return None

    setattr(options, 'pokerpath', pokerpath)

    workpath = fsutils.getParentDir(__file__, 1)
    setattr(options, 'workpath', workpath)

    fpath = os.environ.get('LOGDIR', '')
    if fpath and fsutils.dirExists(fpath):
        fpath = fsutils.abspath(fpath)
        setattr(options, 'logpath', fpath)
        ct = datetime.now().strftime('%Y%m%d%H%M%S')
        actlog.open_act_log(options, {'uuid': ct})
    else:
        setattr(options, 'logpath', None)

    actlog.log("pokerpath =", options.pokerpath)
    actlog.log("workpath  =", options.workpath)
    actlog.log("logpath   =", options.logpath)

    flogfile = fsutils.appendPath(fpath, 'webmagr.log')
    setattr(options, 'logfile', flogfile)

    actlog.log("action    =", options.action)
    if options.action == 'config_check':
        action = {'action': 'config_check', 'params': {}}
        thread_do_action(options, action)
        return

    if options.action == 'config_reload':
        action = {'action': 'config_reload', 'params': {}}
        thread_do_action(options, action)
        return

    if options.action == 'config_update':
        keys = []
        if hasattr(options, 'keys'):
            keys = options.keys.split(',')
        action = {'action': 'config_update', 'params': {'keys': keys}}
        thread_do_action(options, action)
        return

    if options.action == 'config_reset':
        action = {'action': 'config_update', 'params': {'reset': 1}}
        thread_do_action(options, action)
        return

    if options.action == 'config_status':
        action = {'action': 'config_status', 'params': {}}
        thread_do_action(options, action)
        return

    if options.action == 'compile':
        action = {'action': 'compile_source', 'params': {}}
        thread_do_action(options, action)
        return

    if options.action == 'start':
        action = {'action': 'config_compile_start', 'params': {}}
        thread_do_action(options, action)
        return

    if options.action == 'reset':
        if not hasattr(options, 'serverIds'):
            useage()
            actlog.log('You must input -sid XXX,XXX')
            return
        processids = options.serverIds.split(',')
        if not processids:
            useage()
            actlog.log('You must input -sid XXX,XXX')
            return
        action = {'action': 'reset', 'params': {'processids': processids}}
        thread_do_action(options, action)
        return

    if options.action == 'stop':
        action = {'action': 'stop_all_process', 'params': {}}
        thread_do_action(options, action)
        return

    if options.action == 'push_code':
        action = {'action': 'push_bin', 'params': {}}
        thread_do_action(options, action)
        return

    if options.action == 'push_web':
        action = {'action': 'push_web', 'params': {}}
        thread_do_action(options, action)
        return

    hotfixwait = 1
    if options.action == 'hotfix_nowait':
        options.action = 'hotfix'
        hotfixwait = 0
    setattr(options, 'hotfixwait', hotfixwait)

    if options.action == 'hotfix':
        if not hasattr(options, 'serverIds'):
            useage()
            actlog.log('You must input -sid XXX,XXX or -sid all')
            return
        if not hasattr(options, 'hotfixpy'):
            useage()
            actlog.log('You Must input -py xxxx.py')
            return
        hotfix.action(options)
        return

    if options.action == 'rm_logs':
        action = {'action': 'remove_all_logs', 'params': {}}
        thread_do_action(options, action)
        return

    actlog.log('unknow action of :', options.action)
    useage()