Exemple #1
0
    def wrapper(api_request_handler, *args, **kwargs):
        if api_request_handler.env is None:
            error(api_request_handler)
            return
        method_param = api_request_handler.env.req.get_argument('method')
        module_name, method_name = method_param.split('.')

        if method_name in ignore_api_module or method_param in ignore_api_method:
            user_m = api_request_handler.env.user.user_m
            _client = user_m.redis
            lock_key = user_m.make_key_cls(
                'lock.%s.%s' % (user_m.uid, method_param), user_m._server_name)
            now = time.time()
            ts = now + 1
            flag = _client.setnx(lock_key, ts)
            try:
                if not (flag or
                        (now > float(_client.get(lock_key))
                         and now > float(_client.getset(lock_key, ts)))):
                    error(api_request_handler)
                    return
            except:
                import traceback
                print_log(traceback.print_exc())
                error(api_request_handler)
                return

            result = func(api_request_handler, *args, **kwargs)

            if time.time() < float(_client.get(lock_key)):
                _client.delete(lock_key)
        else:
            result = func(api_request_handler, *args, **kwargs)

        return result
Exemple #2
0
def pay_lock(tp, payment, func, args):
    api_tp = ['androidky']

    if tp in api_tp:
        locked = False

        redis = ModelTools.get_redis_client('pay_lock', 'master')

        lock_key = ModelTools.make_key_cls('pay_lock.%s' % tp, 'master')
        now = time.time()
        ts = now + 1
        flag = redis.setnx(lock_key, ts)
        try:
            if not (flag or (now > float(redis.get(lock_key))
                             and now > float(redis.getset(lock_key, ts)))):
                locked = True
        except:
            import traceback
            print_log(traceback.print_exc())

        if locked:
            d = payment.ERROR_RETURN.get(tp)
        else:
            d = func(*args)

        if time.time() < float(redis.get(lock_key)):
            redis.delete(lock_key)
    else:
        d = func(*args)

    return d
Exemple #3
0
def socket_server(host, port):
    print_log(
        __file__, '[%s] start handler_client server on port %s:%s' %
        (get_datetime_str(), host, port))
    server = StreamServer((host, int(port)), request_handler)
    gevent.signal(signal.SIGTERM, close)
    gevent.signal(signal.SIGINT, close)
    server.serve_forever()
Exemple #4
0
def main():
    app = Application()

    import game_config
    print_log(os.getpid(), os.getppid(), options.port)
    try:
        sockets = tornado.netutil.bind_sockets(options.port)
    except socket.error, e:
        os.system('''for i in `ps aux | grep -v 'grep' | grep 'python' | grep 'run.py' | grep 'port=%d' | awk '{if($2!=%d){print $2}}'`;do kill -9 $i;done'''%(options.port, os.getpid()))
        sockets = tornado.netutil.bind_sockets(options.port)
        print_log('killed orphan process')
Exemple #5
0
def start_child(task_id):
    pid = os.fork()
    if pid: # parent proces
        # 父进程则会将子进程pid与子进程对应的i值进行映射,然后返回父进程的pid
        CHILDREN[task_id] = pid
        return pid
    # child process
    signal.signal(signal.SIGTERM, sig_hander_child)     # pid==0 表示子进程
    signal.signal(signal.SIGINT, sig_hander_child)
    print_log(options.server_name, ':', task_id, ':', os.getpid(), 'started')
    return pid
Exemple #6
0
    def initialize(self):
        """ 初始化操作

        创建全局环境和运行环境
        """
        try:
            self.env = APIEnviron.build_env(self)
        except:
            import traceback
            print_log(traceback.print_exc())
            self.env = None
def reload_config(timer_pool, config_name, class_name, force_reload=False):
    """ reload一个配置

    :param timer_pool: TimerPool实例
    :param config_name:  配置名
    :param class_name: TimerTaskBase子类
    :param force_reload: 是否强行加载
    :return:
    """
    timer_pool.lock.acquire()

    version = game_config.config_version.get(config_name, 0)
    doing = []
    del_list = []
    print_log('reload_config start: ', config_name, version)
    for pool_key, timer_task in timer_pool.pool.iteritems():
        if isinstance(timer_task, class_name):
            if timer_task.get_version() == version and not force_reload:
                print_log('reload_config return: ', config_name,
                          timer_task.get_version())
                timer_pool.lock.release()
                return
            # 更新定时脚本
            doing.append(timer_task.get_config_id())
            if timer_task.can_add(CONFIG_TYPE, DEFAULT_GLOBAL_SERVER):
                timer_task.set_version(version)
                timer_task.parser()
                print_log(
                    'reload_config update: ', config_name,
                    datetime.datetime.fromtimestamp(
                        timer_task.get_next_time()))
            else:
                del_list.append(pool_key)
    # 删除无用定时脚本
    for del_key in del_list:
        print_log('reload_config delete: ', del_key)
        del timer_pool.pool[del_key]
    # 添加新的定时脚本
    config = getattr(game_config, config_name, {})
    for config_id in config.iterkeys():
        if config_id not in doing:
            timer_task = class_name(config_id, version)
            if timer_task.can_add(CONFIG_TYPE, DEFAULT_GLOBAL_SERVER):
                timer_task.parser()
                timer_pool.add(timer_task)
                print_log(
                    'reload_config add: ', config_name, config_id,
                    datetime.datetime.fromtimestamp(
                        timer_task.get_next_time()))

    timer_pool.lock.release()
def reload_all_timers(timer_pool):
    """ 更新所有的固定定时脚本

    :param timer_pool:
    :return:
    """
    for k, v in TIMER_CONFIG.iteritems():
        try:
            timer_task = TimerTask(k, v)
            if timer_task.can_add(CONFIG_TYPE, DEFAULT_GLOBAL_SERVER):
                timer_pool.add(timer_task)
                print_log(
                    k, datetime.datetime.fromtimestamp(timer_task.next_time))
        except:
            trackback(msg='timer, add %s ERROR: ' % str(k))
Exemple #9
0
def debug_sync_change_time():
    from lib.utils import change_time
    from models.config import ChangeTime

    delta_seconds = ChangeTime.get()
    delta_seconds = int(float(delta_seconds)) if delta_seconds else 0
    real_time = int(change_time.REAL_TIME_FUNC())
    sys_time = real_time + delta_seconds
    if sys_time != int(time.time()):
        change_time.change_time(sys_time)
        print_log(
            'debug_change_time: %s -- %s -- %s' %
            (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(real_time)),
             time.strftime('%Y-%m-%d %H:%M:%S'), delta_seconds))
        return True

    return False
    def loop(self, ):
        """# start: docstring
        args:
            :    ---    arg
        returns:
            0    ---
        """
        while 1:
            gevent.sleep(1)
            now = time.time()
            self.lock.acquire()

            if self.config_time % 60 == 0:
                # from logics.share import  debug_sync_change_time
                # 注意, 正式环境禁止启动此函数
                if settings.DEBUG:
                    debug_sync_change_time(self)

                if self.is_config_out():
                    game_config.load_all()
                    reload_all_config(self)

            pool_copy = copy.copy(self.pool)
            del_list = []
            for k, task_obj in pool_copy.iteritems():
                if now >= int(task_obj.get_next_time()):
                    try:
                        if task_obj.is_global() == 1:
                            # gevent.joinall([gevent.Greenlet.spawn(task_obj.get_func())], raise_error=True)
                            gevent.joinall(
                                [gevent.Greenlet.spawn(task_obj.get_func())])
                        elif task_obj.is_global() == 2:
                            world_ids = list(
                                set([
                                    value['world_id'] for value in
                                    game_config.server_pk_world.itervalues()
                                ]))
                            for world_id in world_ids:
                                print_log(
                                    'world func: ', task_obj.get_func(),
                                    datetime.datetime.fromtimestamp(
                                        task_obj.next_time))
                                # gevent.joinall([gevent.Greenlet.spawn(task_obj.get_func(), world_id)], raise_error=True)
                                gevent.joinall([
                                    gevent.Greenlet.spawn(
                                        task_obj.get_func(), world_id)
                                ])
                        else:
                            for server_name, server_cfg in settings.SERVERS.iteritems(
                            ):
                                if server_name == 'master': continue
                                # if server_cfg['config_type'] != CONFIG_TYPE: continue
                                if settings.get_config_type(
                                        server_name) != CONFIG_TYPE:
                                    continue
                                print_log(
                                    'func: ', task_obj.get_func(),
                                    datetime.datetime.fromtimestamp(
                                        task_obj.next_time))
                                # gevent.joinall([gevent.Greenlet.spawn(task_obj.get_func(), server_name)], raise_error=True)
                                gevent.joinall([
                                    gevent.Greenlet.spawn(
                                        task_obj.get_func(), server_name)
                                ])
                        timer_model.last_update_timestamp[
                            task_obj.get_key()] = now
                        if task_obj.is_repeat():
                            task_obj.parser()
                            timer_model.next_update_timestamp[
                                task_obj.get_key()] = int(
                                    task_obj.get_next_time())
                        else:
                            del_list.append(k)
                        timer_model.save()
                        print_log('timer, run %s, is_repeat: %s' %
                                  (k, str(task_obj.is_repeat())))
                    except:
                        trackback(msg='timer, timer %s ERROR: ' % str(k))
            for k in del_list:
                del self.pool[k]
            self.config_time += 1
            self.lock.release()
def to_config_string(config_name, data):
    """# to_config_string: docstring
    args:
        data:    ---    arg
    returns:
        0    ---
    """
    template_tuple = getattr(CT, config_name)()
    if len(template_tuple) == 2:
        trans, funcs = template_tuple
    elif len(template_tuple) == 3:
        trans, funcs, check_func_list = template_tuple
    else:
        raise TypeError("to_config_string takes 2 or 3 arguments, (%s)")

    r = []
    for line_no, line in enumerate(data):
        for tran in trans:
            if len(tran) == 3:
                tran_col_name, tran_format, tran_type = tran
                tran_check = None
            else:
                tran_col_name, tran_format, tran_type, tran_check = tran
            tran_check = None
            # if tran_col_name != 'END' and tran_col_name not in line:
            #     continue
            tran_format = tran_format.replace(' ', '')
            if tran_type == 'None':  # 结束标记
                s = tran_format
            elif isinstance(tran_type, tuple):  # 类型为元祖的
                l = []
                try:
                    for i in xrange(len(tran_type)):
                        if isinstance(tran_col_name, tuple):
                            value = line[tran_col_name[i]]
                        else:
                            value = line[tran_col_name + '_' + str(i)]
                        tran_data = mapping[tran_type[i]](value)
                        if tran_check is not None and tran_check[i] is not None:
                            flag = tran_check[i](eval(tran_data))
                            if not flag:
                                raise KeyError("line_no=", line_no, "msg=",
                                               tran_data)
                        l.append(tran_data)

                    s = tran_format % tuple(l)
                except Exception, e:
                    print_log(tran_format, config_name, l)
                    etype, value, tb = sys.exc_info()
                    line = traceback.format_exception_only(etype, value)
                    raise KeyError("line_no=", line_no, "msg=", line)
            else:
                value = line[tran_col_name]
                try:
                    tran_data = mapping[tran_type](value)
                    if tran_check is not None:
                        check_args = eval(tran_data) if isinstance(
                            tran_data, basestring) else tran_data
                        flag = tran_check(check_args)
                        if not flag:
                            raise KeyError("line_no=", line_no, "msg=",
                                           tran_data)
                    s = tran_format % tran_data
                except Exception, e:
                    print_log('lineno: ', line_no, tran_format, config_name,
                              repr(value))
                    print_log('format_exc: ', traceback.format_exc())
                    etype, value, tb = sys.exc_info()
                    line = traceback.format_exception_only(etype, value)
                    raise KeyError("line_no=", line_no, "msg=", line)
            if funcs.get(tran_col_name, lambda x: True)(s):
                r.append(s)
Exemple #12
0
    def api(self):
        """ API统一调用方法
        """
        method_param = self.env.req.get_argument('method')
        module_name, method_name = method_param.split('.')
        ########################################
        # 客户端版本判断
        # game_config.version eg:{'h1': {'msg': u'当前测试已经结束啦。感谢您对《禁区》的支持,我们将于2月中旬进行第二轮测试,敬请期待。',
        #                                 'url': 'http://www.baidu.com',
        #                                 'version': '1.0.1'}
        #                         }
        uid = self.env.req.get_argument('user_token')
        all_server_flag = 'all'
        if uid and (uid[:-7] in game_config.version
                    or all_server_flag in game_config.version):
            data = {
                'url': 'http://www.baidu.com',  # 前端需要跳转到的新包下载地址,一般是官网什么的
                'msg': u'当前测试已经结束啦。感谢您对《禁区》的支持,我们将于2月中旬进行第二轮测试,敬请期待。',
                'version': '',
                'need_upgrade': False
            }

            if settings.ENV_NAME in [
                    settings.ENV_IOS, settings.ENV_STG_IOS,
                    settings.ENV_TEST_IOS
            ]:
                data.update(
                    game_config.version.get(
                        uid[:-7], game_config.version.get(all_server_flag,
                                                          {})))
            else:
                user = self.env.user
                _platform = user.account.split('_')[0].lower()
                _version_config = game_config.version.get(
                    uid[:-7], game_config.version.get(all_server_flag, {}))
                _platform_config = _version_config.get(_platform, [])
                if _platform_config and len(_platform_config) == 3:
                    # [[version], [url], [msg]]
                    data['version'] = _platform_config[0][0]
                    data['url'] = _platform_config[1][0]
                    data['msg'] = _platform_config[2][0]

            version = self.env.get_argument('version', '1.0.2')
            new_version = data.get('version', '')
            if new_version and version < new_version:
                data['need_upgrade'] = True

                d = {
                    'status': 0,
                    'data': {},
                    'msg': '',
                    'user_status': {},
                    'client_upgrade': data
                }
                self.set_header('content_type',
                                'application/json; charset=UTF-8')
                self.set_header('Content-Type',
                                'application/json; charset=UTF-8')
                r = json.dumps(d,
                               ensure_ascii=False,
                               encoding="utf-8",
                               indent=2,
                               default=to_json)
                self.write(r)
                self.finish()
                return -99009, {}, '', None

        ########################################
        # # 清档测试    2014-05-19 17:00:00 之后注册的用户不让进 测试服
        # if 'g1' in self.env.user.uid:
        #     pts = ['downjoy', 'uc', 'pp', 'kuaiyong', 'itools', 'tongbu']
        #     pt = self.env.user.account.split('_')[0]
        #     if self.env.user.regist_time > 1400490000 or pt.lower() in pts:
        #         rc = 'f**k'
        #         d = {
        #             'status': rc,
        #             'data': {},
        #             'msg': game_config.return_msg_config.get(rc, rc),
        #             'user_status': {},
        #         }
        #         self.set_header('content_type', 'application/json; charset=UTF-8')
        #         self.set_header('Content-Type', 'application/json; charset=UTF-8')
        #         r = json.dumps(d, ensure_ascii=False, encoding="utf-8", indent=2, default=to_json)
        #         self.write(r)
        #         self.finish()
        #         return rc, {}, d['msg'], self.env.user

        ########### 封号 start #################
        if self.env.user.is_ban:
            rc = 'error_17173'
            d = {
                'status': rc,
                'data': {},
                'msg': game_config.return_msg_config.get(rc, rc),
                'user_status': {},
            }
            self.set_header('content_type', 'application/json; charset=UTF-8')
            self.set_header('Content-Type', 'application/json; charset=UTF-8')
            r = json.dumps(d,
                           ensure_ascii=False,
                           encoding="utf-8",
                           indent=2,
                           default=to_json)
            self.write(r)
            self.finish()
            return rc, {}, d['msg'], self.env.user
        ########### 封号 end #################

        ########### 多点登录判断 start #################
        device_mark = self.env.get_argument('device_mark', '')
        device_mem = self.env.get_argument('device_mem', '')
        frontwindow = settings.DEBUG or self.env.get_argument(
            'frontwindow', '') == '5e3b4530b293b5c1f4eeca4638ab4dc1'
        mem_unavaible_api = self.env.user.device_mem and self.env.user.device_mem != device_mem
        unavaible_api = self.env.user.device_mark and self.env.user.device_mark != device_mark
        mk = self.env.req.get_argument('mk', 0)
        _mk = int(mk) if mk else 0
        if not frontwindow and (mem_unavaible_api or unavaible_api or not _mk
                                or _mk != self.env.user._mark):
            if module_name not in self.single_login_ignore_api_module and method_param not in self.single_login_ignore_api_method:
                rc = 9527
                d = {
                    'status': rc,
                    'data': {},
                    'msg': game_config.return_msg_config.get(rc, rc),
                    'user_status': {},
                }
                self.set_header('content_type',
                                'application/json; charset=UTF-8')
                self.set_header('Content-Type',
                                'application/json; charset=UTF-8')
                r = json.dumps(d,
                               ensure_ascii=False,
                               encoding="utf-8",
                               indent=2,
                               default=to_json)
                self.write(r)
                self.finish()
                return rc, {}, d['msg'], self.env.user
        ########### 多点登录判断 end #################

        ########### session验证判断 start #################
        ks = self.env.get_argument('ks', '')
        if not frontwindow and settings.SESSION_SWITCH and self.env.user.session_expired(
                ks):
            rc = 9527
            d = {
                'status': rc,
                'data': {},
                'msg': game_config.return_msg_config.get(rc, rc),
                'user_status': {},
            }
            self.set_header('content_type', 'application/json; charset=UTF-8')
            self.set_header('Content-Type', 'application/json; charset=UTF-8')
            r = json.dumps(d,
                           ensure_ascii=False,
                           encoding="utf-8",
                           indent=2,
                           default=to_json)
            self.write(r)
            self.finish()
            return rc, {}, d['msg'], self.env.user
        ########### session验证判断 end #################

        ############## 如果卡包已满,则部分接口直接跳出 #########
        if method_param in self.determine_card_package:
            need_check = True
            param_dict = self.determine_card_package[method_param]
            if param_dict:
                for k, v in param_dict.iteritems():
                    param_value = self.env.req.get_argument(k)
                    if not v or param_value in v:
                        need_check = True
                        break
                else:
                    need_check = False

            if need_check:
                if self.env.user.is_cards_full():
                    from logics import guide

                    rc = 'error_1'
                    guide.mark_guide_4_error(self.env.user, 1)
                    msg = game_config.return_msg_config[rc]
                    data = {
                        '_client_cache_update': {},
                    }
                    self.write(
                        handler_tools.result_generator(rc, data, msg,
                                                       self.env.user))
                    self.finish()
                    return rc, data, msg, self.env.user
                if self.env.user.is_equip_full():
                    rc = 'error_2'
                    msg = game_config.return_msg_config[rc]
                    data = {
                        '_client_cache_update': {},
                    }
                    self.write(
                        handler_tools.result_generator(rc, data, msg,
                                                       self.env.user))
                    self.finish()
                    return rc, data, msg, self.env.user

        ########################################
        user = self.env.user
        old_coin = user.coin
        old_level = user.level

        module = __import__('views.%s' % module_name, globals(), locals(),
                            [method_name])
        method = getattr(module, method_name)

        if callable(method):
            msg = ''
            rc, data = method(self.env)
            if rc != 0:
                msg = data.get('custom_msg', '') or game_config.return_msg_config.get(rc) or \
                    game_config.return_msg_config.get(method_param, {}).get(rc, method_param + '_error_%s' % rc)
                if rc == 'error_14':  # 级别不足 的提示 用后端给的msg
                    rc = 'xx'
            else:
                new_coin = user.con
                # 简单粗暴的记录消费记录
                if new_coin < old_coin:
                    from models.payment import spend_insert
                    arguments = copy.deepcopy(self.env.req.summary_params())
                    for _ in ['method', 'user_token', 'mk']:
                        arguments.pop(_, None)

                    spend_data = {
                        'coin_1st': old_coin,
                        'coin_2nd': new_coin,
                        'coin_num': old_coin - new_coin,
                        'goods_cnname': '',
                        'goods_name': '',
                        'goods_num': 1,
                        'goods_subtype': '',
                        'goods_type': method_param,
                        'level': user.level,
                        'subtime': time.strftime('%F %T'),
                        'uid': user.uid,
                        'args': json.dumps(arguments, separators=(',', ':')),
                    }
                    spend_insert('%s_%s' % (user.uid, time.time()), spend_data)
                    if module_name not in self.single_payment_active_api_module and method_param not in self.single_payment_active_api_method:
                        coin = cal_new_coin(old_coin, new_coin, method_param)
                        # 钻石摩天轮的消耗钻石开启摩天轮的活动
                        try:
                            user.diamond_wheel.pay_coin(coin)
                        except:
                            pass
                        # 开服的钻石摩天轮的消耗钻石开启摩天轮的活动
                        try:
                            user.server_diamond_wheel.pay_coin(coin)
                        except:
                            pass
                        # 赛亚人归来活动
                        user.super_active.add_score(old_coin - new_coin,
                                                    save=True)
                        try:
                            # 新服人归来活动
                            user.server_super_active.add_score(old_coin -
                                                               new_coin,
                                                               save=True)
                        except:
                            pass
                        # 悬赏令消耗的钻石
                        try:
                            user.bounty_order.use_coin(coin)
                        except:
                            import traceback
                            print_log(traceback.print_exc())

                        try:
                            user.server_bounty_order.use_coin(coin)
                        except:
                            import traceback
                            print_log(traceback.print_exc())

                        # 全服神龙消耗的钻石数量
                        try:
                            user.large_super_all.use_coin_or_action_point(
                                coin=coin)
                        except:
                            import traceback
                            print_log(traceback.print_exc())

                        # 全服宇宙最强消耗的钻石数量
                        try:
                            user.large_super_rich.use_coin_or_action_point(
                                coin=coin)
                        except:
                            import traceback
                            print_log(traceback.print_exc())

                        # 开服充值活动
                        user.server_active_recharge.reward_coin(old_coin -
                                                                new_coin)
                        user.consume_reward.add_score(old_coin - new_coin,
                                                      method_param)

                        if 'foundation.activate' not in method_param:
                            #消费钻石,领取奖励活动
                            user.active_consume.add_consume_coin(coin)

                # 用户到2级才回调积分墙接口
                if old_level < user.level and user.level in [2, 3, 4, 5]:
                    from views import ad_click
                    ad_click.ad_callback(self, user.level)

            self.set_header('content_type',
                            'application/javascript; charset=UTF-8')
            self.set_header('Content-Type',
                            'application/javascript; charset=UTF-8')

            # 关于客户端数据缓存的更新
            client_cache_update = {}
            for k, v in self.env.user.__class__.__dict__.iteritems():
                if 'fget' in dir(v) and k not in self.env.user.user_m._attrs:
                    obj = getattr(self.env.user, '_' + k, None)
                    if obj and getattr(obj, '_diff', None):
                        client_cache_update[k] = obj._client_cache_update()

            data['_client_cache_update'] = client_cache_update
            # self.env.user.reward.do_task_api(method_param, self.env, rc, data)
            # self.env.user.daily_score.do_daily_score_api(method_param, self.env, rc, data)
            # try:
            #     self.env.user.recall_daily_score.do_daily_score_api(method_param, self.env, rc, data)
            # except:
            #     import traceback
            #     print_log(traceback.print_exc())
            # self.env.user.bounty_order.do_task_api(method_param, self.env, rc, data)
            # self.env.user.server_bounty_order.do_task_api(method_param, self.env, rc, data)
            # self.env.user.role_reward.do_role_reward_api(method_param, self.env, rc, data)
            self.write(
                handler_tools.result_generator(rc, data, msg, self.env.user))
            self.finish()
            return rc, data, msg, self.env.user
Exemple #13
0
 i = 1
 for i in xrange(1, process_sum+1):
     pid = start_child(i)
     if pid == 0:
         parent = False
         break
 if parent and process_sum:
     signal.signal(signal.SIGTERM, sig_hander_parent)
     signal.signal(signal.SIGINT, sig_hander_parent)
     signal.signal(signal.SIGCHLD, signal.SIG_IGN)   # let init clear zombie child
     # print CHILDREN
     while 1:
         time.sleep(5)
         print CHILDREN
         if not game_config.is_config_out():
             print_log('config out')
             game_config.load_all()
             for task_id in CHILDREN.iterkeys():
                 print_log('config out, restart '+str(task_id))
                 if not restart_child(task_id):
                     parent = False
                     break
         if not parent:
             break
         for task_id, pid in CHILDREN.iteritems():   # if child is alive
             try:
                 child_process = psutil.Process(pid)
                 if not child_process.is_running() or os.getpid() != child_process.ppid():
                     print_log('NO this child, ', task_id, pid, child_process.is_running(), child_process.pid, os.getpid(), child_process.ppid())
                     raise psutil.NoSuchProcess(pid)
                 #mem_watcher(child_process)
Exemple #14
0
def request_handler(client_socket, addr):

    global messages_cache

    now = int(time.time())
    client = Client(client_socket)
    client_manager.add_client(client)

    client_manager.lose_time_out_clients(now)

    print_log('[%s]' % get_datetime_str(), 'connected from %s:%s' % addr,
              'client_socked_fd:', client.fileno)
    print_log('clients_num :', client_manager.get_client_count())

    while True:
        try:
            data = client_socket.recv(BUFFSIZE)
        except:
            client_manager.lose_client(client)
            break

        if not data:
            print_log('[%s]' % get_datetime_str(),
                      'client %s:%s disconnected' % addr,
                      'flag: %s, %s' % (data, type(data)))
            client_manager.lose_client(client)
            print_log('clients_num :', client_manager.get_client_count())
            break

        if data.strip().lower() == 'check':
            now = int(time.time())
            client_socket.sendall(str(process.get_memory_info()) + '|')
            client_socket.sendall('\nclients_num : %s;' %
                                  client_manager.get_client_count())
            client_socket.sendall(
                '\nper_client_connect_time: "[(fileno, uid, game_id, '
                'guild_id, server_name, vip, domain, team_id, live_time)]--> %s";'
                % str(
                    sorted([(x, y.uid, y.game_id, y.guild_id, y.server_name,
                             y.vip, y.domain, y.team_id, now - y.ttl)
                            for x, y in client_manager._clients.iteritems()],
                           key=lambda x: x[1],
                           reverse=True)))
            client_socket.sendall('\n')
            continue

        if data.strip().lower() == 'check_contents':
            client_socket.sendall(
                str(process.get_memory_info()) + '|' +
                str(id(content_factory)))
            client_socket.sendall('\ncontents : %s;' % repr([
                content.__dict__
                for content in content_factory._contents.itervalues()
            ]))
            client_socket.sendall('\n')
            continue

        if data.strip().lower() == 'quit':
            client_manager.lose_client(client)
            break

        # buffer超了指定大小还未找到规定格式的数据,主动断开连接
        if len(client.buffer) >= MAX_BUFFER_SIZE:
            client_manager.lose_client(client)
            break

        info = client.parse(data)

        if not info:
            continue

        tp = info['kqgFlag']
        if tp == 'first':
            try:
                u = User.get(info.get('uid'))
            except:
                client_manager.lose_client(client)
                break

            # if u.session_expired(info.get('ks')) or (u.device_mark and u.device_mark != info.get('device_mark'))\
            #         or (u.device_mem and u.device_mem != info.get('device_mem')):
            #     client_manager.lose_client(client)
            #     continue

            if u.is_ban:
                client_manager.lose_client(client)
                break

            client.init_info(info.get('uid'), info.get('association_id', ''),
                             info.get('game_id', ''), info.get('vip', 0),
                             info.get('domain', ''), info.get('team_id', ''),
                             addr[0], info.get('sid'), info.get('device_mark'),
                             info.get('device_mem'))

            client_manager.add_server_client(client)
            # if client.vip >= 8:
            #     receivers_vip = []
            #     for _fd, _client in client_manager.get_client_by_server_name(client.server_name).items():
            #         if _fd != client.fileno:
            #             receivers_vip.append(gevent.spawn(_client.socket.sendall, client.msg))
            #     gevent.joinall(receivers_vip)
            #
            #     content = content_factory.get(content_factory.MAPPINGS['world'], client.server_name)
            #     content.add(client.msg)
            if GAG_MSG_SWITCH:
                client.socket.sendall(force_str(get_default_msg()))

            if not GAG_MSG_SWITCH:
                content = content_factory.get(
                    content_factory.MAPPINGS['world'], client.server_name)
                msgs = content.show()
                if msgs:
                    client.socket.sendall(''.join(msgs))

                content_friend = content_factory.get(
                    content_factory.MAPPINGS['friend'], client.server_name,
                    client.uid)
                msgs = content_friend.get(client.uid)
                content_factory.delete(content_factory.MAPPINGS['friend'],
                                       client.server_name, client.uid)
                if msgs:
                    client.socket.sendall(''.join(msgs))

                client_manager.lose_repeat_clients(client)
            continue

        if tp == 'update':
            client.update_info(info.get('association_id'), info.get('domain'),
                               info.get('team_id'))

        if GAG_MSG_SWITCH:
            continue

        if client.uid in GAG_UIDS:
            continue

        u = User.get(client.uid)
        if not settings.SESSION_SWITCH and u.ip and u.ip != client.ip:
            continue

        if settings.SESSION_SWITCH and (
                u.session_expired(info.get('ks')) or
            (u.device_mark and u.device_mark != info.get('device_mark')) or
            (u.device_mem and u.device_mem != info.get('device_mem'))):
            continue

        if u.is_ban:
            continue

        next_flag = info.get('next')
        if next_flag and tp in ['world', 'system', 'guild'
                                ] and next_flag in [1, 2]:
            content = content_factory.get(content_factory.MAPPINGS[tp],
                                          client.server_name)
            msgs = content.show(next_flag)
            if msgs:
                client.socket.sendall(''.join(msgs))
            continue

        con_name = content_factory.MAPPINGS.get(tp)
        if con_name and tp not in content_factory.IGNORE:
            content = content_factory.get(con_name, client.server_name)
            content.add(client.msg)

        sendToUid = info.get('sendToUid', '')
        receivers = []
        for _fd, _client in client_manager.get_client_by_server_name(
                client.server_name).iteritems():
            if _fd == client.fileno:
                continue
            # 判断消息是否需要发送  用gevent.spawn 处理
            if tp in ['world', 'system']:  # 世界, 系统
                receivers.append(
                    gevent.spawn(_client.socket.sendall, _client.msg))
            elif tp == 'guild':  # 公会
                if _client.guild_id and _client.guild_id == client.guild_id:
                    receivers.append(
                        gevent.spawn(_client.socket.sendall, client.msg))
            elif tp == 'friend' and _client.uid == sendToUid:  # 好友
                receivers.append(
                    gevent.spawn(_client.socket.sendall, client.msg))
                break
            elif tp == 'guild_war':  # 工会战
                if _client.guild_id and client.guild_id:
                    receivers.append(
                        gevent.spawn(_client.socket.sendall, client.msg))
            elif tp in ['rob', 'escort']:  # 运镖, 打劫
                if client.domain and client.domain == _client.domain:
                    receivers.append(
                        gevent.spawn(_client.socket.sendall, client.msg))
            elif tp == 'team':  # 队伍
                if client.team_id and client.team_id == _client.team_id:
                    receivers.append(
                        gevent.spawn(_client.socket.sendall, client.msg))

        # 私聊缓存
        if tp == 'friend' and sendToUid and not receivers:
            content = content_factory.get(content_factory.MAPPINGS[tp],
                                          client.server_name, sendToUid)
            content.add(client.msg)
            # content.save()

        gevent.joinall(receivers)
Exemple #15
0
def kill_child(task_id):
    pid = CHILDREN[task_id]
    print_log(options.server_name, ':', task_id, ':', pid, 'ending....')
    os.kill(pid, signal.SIGTERM)
    #os.waitpid(pid, 0)
    CHILDREN[task_id] = None
Exemple #16
0
 def check_config():
     if not game_config.is_config_out():
         print_log('config out')
         game_config.load_all()
Exemple #17
0
    def api(self):
        """ API统一调用方法
        """
        user = self.hm.mm.user
        """
        # ########## 封号 start #################
        ban_info = user.get_ban_info()
        if ban_info:
            return self.result_info('error_17173', {'custom_msg': ban_info})
        # ########## 封号 end #################

        # ########## 封ip start #################
        uip = self.hm.req.request.headers.get('X-Real-Ip', '') or self.hm.req.request.remote_ip
        banip_info = user.get_banip_info(uip)
        if banip_info:
            return self.result_info('error_17173', {'custom_msg': banip_info})
        # ########## 封ip end #################
        """

        method_param = self.get_argument('method')
        module_name, method_name = method_param.split('.')

        try:
            module = importlib.import_module('views.%s' % module_name)
        except ImportError:
            print_log(traceback.print_exc())
            return self.result_info('error_module')

        method = getattr(module, method_name, None)
        if method is None:
            return self.result_info('error_method')

        if callable(method):
            pre_status, pre_data = self.pre_handler()
            if pre_status:
                return self.result_info(pre_status, pre_data)

            rc, data = method(self.hm)
            # call_status 只有rc不为0时, 可以传call_status True: 代表执行成功  False: 代表执行失败
            if rc != 0 and not data.get('call_status', False):
                return self.result_info(rc, data)

            post_status = self.post_handler()
            if post_status:
                return self.result_info(post_status, data)

            client_cache_udpate = {}
            old_data = {}

            if self.hm.mm:
                if method_param not in ['user.get_red_dot', 'user.game_info']:
                    cur_lan_sort = self.get_argument('lan', '1')
                    if cur_lan_sort != self.hm.mm.user.language_sort:
                        self.hm.mm.user.language_sort = cur_lan_sort
                    self.hm.mm.user.update_active_time(self.request)
                    self.hm.mm.user.save()
                """
                # 主线任务,支线任务自动领奖
                mission_award = {}
                if method_param in self.AUTO_RECEIVE_MISSION_AWARD_FUNC:
                    mission_award = self.hm.mm.mission_main.auto_receive_award()
                    if mission_award:
                        data['_mission_main'] = mission_award

                if mission_award or method_param in self.MISSION_TASK_UPDATE_FUNC:
                    data['mission_task'] = self.hm.mm.mission_main.get_main_tasks()
                    data['side_task'] = self.hm.mm.mission_side.get_side_tasks(filter=True)
                """
                # 执行成功保存数据
                self.hm.mm.do_save()

                # 关于客户端数据缓存的更新
                for k, obj in self.hm.mm._model.iteritems():
                    if obj and obj.uid == self.hm.uid and getattr(
                            obj, '_diff', None):
                        client_cache_udpate[
                            obj._model_name] = obj._client_cache_update()
                        old_data[k] = getattr(obj, '_old_data', {})

            data['_client_cache_update'] = client_cache_udpate
            data['old_data'] = old_data
            return self.result_info(rc, data)
        return self.result_info('error_not_call_method')