Example #1
0
def server_edit(request, server_id=0):
    '''服务器编辑
    '''
    server_id = int(
        request.REQUEST.get('sid', '') or request.REQUEST.get('server_id', '')
        or 0)
    is_copy = request.REQUEST.get('copy', '')
    if server_id:
        model = Server.objects.using('read').get(id=server_id)
        if is_copy:
            model.name = ''
            model.game_addr = ''
            model.model = ''
    else:
        model = Server()
        model.id = 0
    list_group = Group.objects.all()

    # 分组名称
    m = eval(
        DictValue.objects.using('read').get(dict_id=tab_name_id).json_dict)

    # 所属分组ID
    if server_id:
        tab_id = str(model.tabId)

    return render_to_response('server/server_edit.html', locals())
Example #2
0
    def __get_server_and_member(self, discord_server, discord_user):
        member = Member.objects(discord=discord_user.id).first()
        server = Server.objects(id=discord_server.id).first()

        if not server:
            server = Server.create({
                'id': discord_server.id,
                'name': discord_server.name,
                'avatar': discord_server.icon_url or ''
            })

        if not member:
            member = Member.create({
                'discord': discord_user.id,
                'name': discord_user.name,
                'avatar': discord_user.avatar_url or ''
            })

        # Checks if member being added is in the server
        server_member = Member.objects(servers=discord_server.id,
                                       discord=discord_user.id).first()
        if not server_member:
            server.members.append(member)
            server.save()
            member.servers.append(discord_server.id)
            member.save()

        return (server, member)
Example #3
0
def create_server(name, hostname, **kwargs):
    """
    Create a server in the database with the given values.
    """
    # TODO Auditable stuff
    existing_server = maybe_get_server_by_hostname(hostname)
    if existing_server:
        raise ServerAlreadyExistsError("A server with this hostname already exists.")
    server = Server(name=name, hostname=hostname)
    server.save()
    return server
Example #4
0
def create_server(operator, name, hostname, **kwargs):
    """
    Create a server in the database with the given values.
    """
    existing_server = maybe_get_server_by_hostname(hostname)
    if existing_server:
        raise ServerAlreadyExistsError("A server with this hostname already exists.")
    server = Server(name=name, hostname=hostname, lowercase_name=name.lower())
    server.save()
    activity_log.log_server_created(server, operator)
    return server
Example #5
0
def log_dbsql(request):
    '''获取分服sql语句接口
    '''
    #根据服务器获取分服数据库所需的SQL结构表信息
    server_id = int(request.GET.get('server_id', '') or 0)
    is_truncate_table = request.REQUEST.get('truncate','') == 'true'
    if not server_id:
        return HttpResponse('服务器不存在,请求失败.')
    sqls = []
    the_server = Server()
    the_server.id = server_id
    sqls.append(the_server.get_base_database_sql())        #创建数据库
    sqls.append('USE %s;' % the_server.db_name)
    if is_truncate_table:
        '''清数据的接口
        '''
        sqls.extend( LogDefine.get_truncate_table_sqls() )
        sqls.append('truncate table player_%d;' % server_id)
    else: 
        sqls.extend(the_server.get_create_player_table_sqls()) #创建player_表
        sqls.extend(the_server.get_create_gang_table_sqls())   #创建gang_表
        sqls.append(the_server.get_drop_base_log_sql())        #先删除下log基表
        sqls.append(the_server.get_create_base_log_sql())      #创建log_x基表
        
        log_defs = LogDefine.objects.filter(status=LogDefine.Status.NORMAL)
        for log_def in log_defs:
                sqls.append(log_def.get_create_table_sql())
                for create_index_sql in log_def.get_create_index_sqls(): #同步索引
                    sqls.append(create_index_sql)  
        for log_def in log_defs:
            for other_sql in log_def.get_other_sqls(is_sql_file=True): #触发器
                sqls.append(sql_handle(other_sql,server_id))
    
    return HttpResponse('\n'.join(sqls))
Example #6
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        nickname = self.get_current_nickname()

        # 列表包str格式,str空格切割
        if not data:
            return self.write(dict(code=-1, msg='不能为空'))

        # 记录下操作,即使报错也不影响程序
        try:
            with DBContext('w', None, True) as session:

                new_record = AssetOperationalAudit(username=nickname,
                                                   request_object='主机',
                                                   request_method='批量添加',
                                                   modify_data=data)
                session.add(new_record)
        except Exception as err:
            ins_log.read_log('error',
                             'operational_audit error:{err}'.format(err=err))

        # 判断下格式长度
        with DBContext('w', None, True) as session:
            for i in data:
                if i:
                    server_info = i.split(' ')
                    ins_log.read_log(
                        'info', 'MultiServer:{server_info}'.format(
                            server_info=server_info))
                    if len(server_info) != 4:
                        return self.write(dict(code=-2, msg='格式错误'))
                    hostname = server_info[0]
                    ip = server_info[1]
                    port = server_info[2]
                    admin_user = server_info[3]
                    if not check_ip(ip):
                        return self.write(dict(code=-1, msg="IP格式不正确"))

                    if not type(port) is int and int(port) >= 65535:
                        return self.write(dict(code=-1, msg="端口格式不正确"))

                    exist_id = session.query(
                        Server.id).filter(Server.hostname == hostname).first()
                    exist_ip = session.query(
                        Server.id).filter(Server.ip == ip).first()
                    if exist_id or exist_ip:
                        return self.write(
                            dict(code=-2,
                                 msg='IP:{ip}/Hostname:{hostname}已经存在,不要重复记录'.
                                 format(ip=ip, hostname=hostname)))

                    new_server = Server(hostname=hostname,
                                        ip=ip,
                                        port=int(port),
                                        admin_user=admin_user)
                    session.add(new_server)

            session.commit()

        return self.write(dict(code=0, msg='批量添加成功'))
Example #7
0
 def add_servers_ip(self):
     # 超过N个角色后封禁账号IP,这个N是从banip_list的f2来的
     server_list = Server.get_server_list()
     count = int(BanIpList.objects.filter(id=1)[0].f2) or 0
     if not count:
         print u'没有设定超过数'
         return
     for s in server_list:
         player_ip_list = self.get_player_list(s.id, count)
         if not player_ip_list:
             continue
         for i in player_ip_list:
             _bm = BanIpList.objects.filter(ip=i[0])
             if not _bm:
                 model = BanIpList()
                 model.username = i[2]
                 model.ip = i[0]
                 model.last_time = datetime.datetime.now()
                 model.f1 = 0
                 model.f2 = i[1]
                 model.status = 0
                 model.save(using="write")
                 continue
             _bm = _bm[0]
             _ip = _bm.ip
             _bm.f2 = i[1]
             _bm.last_time = datetime.datetime.now()
             _bm.save(using="write")
Example #8
0
def log_clear(request, server_id=0, log_type=0, clear_type=0):
    '''清除日志数据
    '''
    server_id = int(server_id)
    log_type = int(log_type)
    clear_type = int(clear_type)
    err_msg = ''
    if log_type > 0 :
        log_def = LogDefine.objects.get(id=log_type)
        try:
            if server_id > 0:
                try:
                    conn = Server.get_conn(server_id)
                except:
                    err_msg = '数据库链接出错!'
            else:
                conn = connection
            if clear_type == 0:
                sql = 'delete from log_%s' % log_def.key
            else:
                sql = 'drop table log_%s' % log_def.key
            cursor = conn.cursor()
            cursor.execute(sql)
            cursor.close()
        except Exception, e:
            print('clear data error:%s' % e)
Example #9
0
def conn_switch(server_id):
    conn = None
    if 0 != server_id:
        conn = Server.get_conn(server_id)
    else:
        conn = connections['write']
    return conn
Example #10
0
 def rename(self):
     from_full = str(self.user)
     self.user.rename(self.params.nick)
     targets = [self.actor] + Server.all()
     for channel in self.user.channels:
         targets += channel.users
     return M(ActorCollection(targets),
              'NICK', self.params.nick,
              prefix=from_full)
Example #11
0
 def rename(self):
     from_full = str(self.user)
     self.user.rename(self.params.nick)
     targets = [self.actor] + Server.all()
     for channel in self.user.channels:
         targets += channel.users
     return M(ActorCollection(targets),
              'NICK', self.params.nick,
              prefix=from_full)
Example #12
0
def __get_or_create_server(session, discord_server_id):
    server = session.query(Server).filter(
        Server.discord_server_id == discord_server_id).one_or_none()

    if server is None:
        server = Server(discord_server_id=discord_server_id)
        session.add(server)

    return server
Example #13
0
    def sync_cmdb(self):
        """
        返回结果写入CMDB
        :return:
        """
        server_list = self.get_server_info()

        if not server_list:
            print('Not Fount Server Info')
            return False

        with DBContext('w') as session:
            for server in server_list:
                ip = server.get('public_ip')
                private_ip = server.get('private_ip')
                instance_id = server.get('instance_id', 'Null')
                hostname = server.get('hostname', instance_id)
                if not hostname.strip():
                    hostname = instance_id
                if re.search('syncserver', hostname):
                    hostname = '{}_{}'.format(hostname, private_ip)

                region = server.get('region', 'Null')
                instance_type = server.get('instance_type', 'Null')
                instance_state = server.get('instance_state', 'Null')
                cpu = server.get('cpu', 'Null')
                cpu_cores = server.get('cpu_cores', 'Null')
                memory = server.get('memory', 'Null')
                disk = server.get('disk', 'Null')
                os_type = server.get('os_type', 'Null')
                os_kernel = server.get('os_kernel', 'Null')
                sn = server.get('sn', 'Null')

                exist_hostname = session.query(Server).filter(Server.hostname == hostname).first()
                exist_ip = session.query(Server).filter(Server.ip == ip).first()

                if not exist_hostname and not exist_ip:
                    new_serve = Server(ip=ip, public_ip=ip, private_ip=private_ip, hostname=hostname, port=22,
                                       idc=self.account, region=region,
                                       state=self.state,
                                       admin_user=self.default_admin_user)
                    new_serve_detail = ServerDetail(ip=ip, instance_id=instance_id, instance_type=instance_type,
                                                    instance_state=instance_state, cpu=cpu, cpu_cores=cpu_cores,
                                                    memory=memory,
                                                    disk=disk, os_type=os_type, os_kernel=os_kernel, sn=sn)
                    session.add(new_serve)
                    session.add(new_serve_detail)
                else:
                    session.query(Server).filter(Server.hostname == hostname).update(
                        {Server.ip: ip, Server.private_ip: private_ip, Server.public_ip: ip, Server.idc: self.account,
                         Server.region: region,
                         Server.admin_user: self.default_admin_user})
                    session.query(ServerDetail).filter(ServerDetail.ip == ip).update(
                        {ServerDetail.instance_id: instance_id, ServerDetail.instance_type: instance_type,
                         ServerDetail.instance_state: instance_state})

            session.commit()
Example #14
0
File: ec2.py Project: brucct/codo
    def sync_cmdb(self):
        """
        写入CMDB
        :return:
        """

        server_list = self.get_server_info()
        if not server_list:
            ins_log.read_log('info', 'Not fount server info...')
            # print('Not Fount Server Info')
            return False
        with DBContext('w') as session:
            for server in server_list:
                ins_log.read_log('info', '资产信息:{}'.format(server))
                ip = server.get('public_ip')
                instance_id = server.get('instance_id', 'Null')
                hostname = server.get('hostname', instance_id)
                if not hostname.strip():
                    hostname = instance_id
                region = server.get('region', 'Null')
                instance_type = server.get('instance_type', 'Null')
                instance_state = server.get('instance_state', 'Null')
                # AWS=接口没看到CPU这类信息
                cpu = server.get('cpu', 'Null')  # CPU型号
                cpu_cores = server.get('cpu_cores', 'Null')
                memory = server.get('memory', 'Null')
                disk = server.get('disk', 'Null')
                os_type = server.get('os_type', 'Null')
                os_kernel = server.get('os_kernel', 'Null')
                sn = server.get('sn', 'Null')

                exist_hostname = session.query(Server).filter(Server.hostname == hostname).first()
                # exist_ip = session.query(Server).filter(Server.ip == ip).first()
                if exist_hostname:
                    session.query(Server).filter(Server.hostname == hostname).update(
                        {Server.ip: ip, Server.public_ip: ip, Server.idc: 'AWS', Server.region: region})

                else:
                    new_server = Server(ip=ip, public_ip=ip, hostname=hostname, port=22, idc=self.account,
                                        region=region,
                                        state=self.state, admin_user=self.default_admin_user)
                    session.add(new_server)

                exist_ip = session.query(ServerDetail).filter(ServerDetail.ip == ip).first()
                if exist_ip:
                    session.query(ServerDetail).filter(ServerDetail.ip == ip).update(
                        {ServerDetail.instance_id: instance_id, ServerDetail.instance_type: instance_type,
                         ServerDetail.instance_state: instance_state})
                else:
                    new_serve_detail = ServerDetail(ip=ip, instance_id=instance_id, instance_type=instance_type,
                                                    instance_state=instance_state, cpu=cpu, cpu_cores=cpu_cores,
                                                    memory=memory, disk=disk, os_type=os_type, os_kernel=os_kernel,
                                                    sn=sn)
                    session.add(new_serve_detail)
            session.commit()
Example #15
0
def log_syncdb(request, server_id=0):
    '''同步表界面
    '''
    err_msg = ''
    action = request.REQUEST.get('action','')
    server_ids = request.REQUEST.getlist('sid')
    if action == 'syncdb':
        return log_syncdb_do(request)
    if server_ids:
        if int(server_ids[0]) == 0:
            center_server = Server()
            center_server.id = 0
            center_server.name = '中央服'
            list_record = [center_server]
        else:
            list_record = Server.objects.using('read').filter(id__in=server_ids)
    else:
        err_msg = '没有选择服务器!'

    return render_to_response('log/log_sync_status.html', locals())
Example #16
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        hostname = data.get('hostname', None)
        port = data.get('port', 22)
        public_ip = data.get('public_ip', None)
        private_ip = data.get('private_ip', None)
        idc = data.get('idc', None)
        admin_user = data.get('admin_user', None)
        region = data.get('region', None)
        state = data.get('state', 'new')
        tag_list = data.get('tag_list', [])
        detail = data.get('detail', None)

        if not hostname or not public_ip or not port:
            return self.write(dict(code=-1, msg='关键参数不能为空'))

        if not admin_user:
            return self.write(dict(code=-1, msg='管理用户不能为空'))

        if not check_ip(public_ip):
            return self.write(dict(code=-1, msg="IP格式不正确"))

        if not type(port) is int and int(port) >= 65535:
            return self.write(dict(code=-1, msg="端口格式不正确"))

        with DBContext('r') as session:
            exist_id = session.query(
                Server.id).filter(Server.hostname == hostname).first()
            exist_ip = session.query(
                Server.id).filter(Server.public_ip == public_ip).first()
        if exist_id or exist_ip:
            return self.write(dict(code=-2, msg='不要重复记录'))

        with DBContext('w', None, True) as session:
            new_server = Server(hostname=hostname,
                                public_ip=public_ip,
                                private_ip=private_ip,
                                port=int(port),
                                idc=idc,
                                admin_user=admin_user,
                                region=region,
                                state=state,
                                detail=detail)
            session.add(new_server)

            all_tags = session.query(Tag.id).filter(
                Tag.tag_name.in_(tag_list)).order_by(Tag.id).all()
            # print('all_tags', all_tags)
            if all_tags:
                for tag_id in all_tags:
                    session.add(
                        ServerTag(server_id=new_server.id, tag_id=tag_id[0]))

        return self.write(dict(code=0, msg='添加成功'))
Example #17
0
def log_server(request, log_id=0):
    if log_id > 0 :
        log_def = LogDefine.objects.get(id=log_id)
    
    list_server = Server.get_server_list()
    
    parg = {}
    parg["list_server"] = list_server
    parg["log_def"] = log_def
    
    return render_to_response('log/log_server.html', parg)
Example #18
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        nickname = self.get_current_nickname()
        hostname = data.get('hostname', None)
        ip = data.get('ip', None)
        port = data.get('port', 22)
        public_ip = data.get('public_ip', None)
        idc = data.get('idc', None)
        admin_user = data.get('admin_user', None)
        region = data.get('region', None)
        state = data.get('state', 'new')
        tag_list = data.get('tag_list', [])
        detail = data.get('detail', None)

        if not hostname or not ip or not port:
            return self.write(dict(code=-1, msg='关键参数不能为空'))

        if not admin_user:
            return self.write(dict(code=-1, msg='管理用户不能为空'))

        if not check_ip(ip):
            return self.write(dict(code=-1, msg="IP格式不正确"))

        if not type(port) is int and int(port) >= 65535:
            return self.write(dict(code=-1, msg="端口格式不正确"))

        with DBContext('r') as session:
            exist_id = session.query(Server.id).filter(Server.hostname == hostname).first()
            exist_ip = session.query(Server.id).filter(Server.ip == ip).first()
        if exist_id or exist_ip:
            return self.write(dict(code=-2, msg='不要重复记录'))

        with DBContext('w', None, True) as session:
            new_server = Server(hostname=hostname, ip=ip, public_ip=public_ip, port=int(port), idc=idc,
                                admin_user=admin_user, region=region, state=state, detail=detail)
            session.add(new_server)

            all_tags = session.query(Tag.id).filter(Tag.tag_name.in_(tag_list)).order_by(Tag.id).all()
            # print('all_tags', all_tags)
            if all_tags:
                for tag_id in all_tags:
                    session.add(ServerTag(server_id=new_server.id, tag_id=tag_id[0]))

        # 记录,记录错误也不要影响用户正常添加
        try:
            with DBContext('w', None, True) as session:

                new_record = AssetOperationalAudit(username=nickname, request_object='主机', request_host=ip,
                                                   request_method='新增', modify_data=data)
                session.add(new_record)
        except Exception as err:
            ins_log.read_log('error', 'operational_audit error:{err}'.format(err=err))

        return self.write(dict(code=0, msg='添加成功'))
Example #19
0
def get_player_info(server_id, player_ids):
    """获取玩家信息(单个)"""
    conn = Server.get_conn(server_id)
    cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
    sql = '''select player_id,player_name,channel_id,user_type,link_key,login_num,mobile_key,last_time,create_time,status,other
    from player_%s p WHERE player_id in (%s)''' % (server_id,
                                                   ','.join(player_ids))
    cur.execute(sql)
    data_list = cur.fetchall()
    conn.close()
    return data_list
Example #20
0
 def __init__(self,sdate,edate,statistics,platform_keys=[],is_create_time=False):
     self.platforms = PlatForm.objects.filter(key__in=platform_keys) if platform_keys else  PlatForm.objects.all()
     self.statistics = [ str(x) for x in statistics]
     self.statistics_models_list = Statistic.objects.filter(id__in=[int(x) for x in self.statistics])
     self.sdate = sdate
     self.edate = edate
     self.center_con = Server.get_conn(0,connect_timeout=10)
     self.center_con.autocommit(False)
     
     self.is_create_time = is_create_time
     if self.is_create_time : #如果是按生成时间获取的 话,限制在开始时间内
         self.sdate = datetime.datetime(self.sdate.year,self.sdate.month,self.sdate.day,0,0,0,0)
Example #21
0
def log_data_delete(request, log_type):
    
    log_type = int(log_type)
    
    sdate = request.GET.get('sdate','')
    edate = request.GET.get('edate','')
    server_id = int(request.GET.get('server_id','0'))
    
    delete_date = ''
    size = 300
    msg = ''

    if server_id > 0:
        delete_server = " AND `log_server` = %d " % server_id
    else:
        msg = '服务器ID不能为空!'  
            
    if sdate != '' and edate != '':
        delete_date +=  "`log_time` >='%s' AND `log_time` <= '%s' " %(sdate, edate) 
        print delete_date
        
    else:
        msg = '时间不能为空!'     
        
    is_finish = 0
    record = 0
    if log_type > 0 and msg == '':
        print 'yes'
        log_def = LogDefine.objects.get(id=log_type)
        try:
            if server_id > 0:
                try:
                    conn = Server.get_conn(server_id)
                except:
                    msg = '数据库链接出错!'
                    print msg
            else:
                conn = connection
            cursor = conn.cursor()
            
            record_sql = "SELECT COUNT(*) FROM `log_%s` WHERE %s %s"%(log_def.key, delete_date, delete_server)
            print record_sql
            cursor.execute(record_sql)
            record = int(cursor.fetchone()[0])
            if record > 0:
                sql = 'DELETE FROM `log_%s` WHERE %s %s LIMIT %d' % (log_def.key, delete_date, delete_server,size)
                is_finish = cursor.execute(sql)
            else:
                is_finish = 0
            cursor.close()
        except Exception, e:
            print('clear data error:%s' % e)    
            msg = '%s'%e
Example #22
0
def sync_log_index(request, server_id=0):
    if server_id == 0:
        server_id = int(request.GET.get('server_id', '0'))
    
    log_list = []
    server_list = []
    if server_id == 0:
        log_list = LogDefine.objects.filter(status = LogDefine.Status.CENTER)
    else:
        server_list = Server.get_server_list()
        log_list = LogDefine.objects.filter(status = LogDefine.Status.NORMAL)
        
    return render_to_response('log/sync_log_index.html', {"server_id": server_id, "log_list": log_list, "server_list":server_list})
Example #23
0
def conference_send_mail(request, template="game/conferen_send_mail.html"):
    server_id = int(request.REQUEST.get("server_id", '') or 0)
    send_type = int(request.REQUEST.get('send_type', '') or 0)
    player_ids = request.REQUEST.get("player_ids", '')  # 角色列表 格式 x1,x2,
    msg = request.REQUEST.get("msg", '')
    send_text = request.REQUEST.get('send_text', '')

    select_channel_ids = []
    agent_channels_dict = get_agent_channels_dict(request)  ###获取全部渠道和agent
    print "22222222222", request.admin.role.first(
    ).resource_ids, player_ids  #############admin.id就是agent
    if player_ids:
        player_ids = json.loads(player_ids)
    if msg:
        _r = {'code': -1, 'msg': '', 'succ': [], 'fail': []}
        # 保存邮件内容
        try:
            con = Server.get_conn(server_id)  #######连接分服的数据库
            cur = con.cursor()
            sql = "select channel_id from player_%s where player_id =%s" % (
                server_id, player_ids[0])  ###分服获取当前渠道
            cur.execute(sql)
            res = cur.fetchall()
            cha_id = int(res[0][0]) if res[0][0] else 0
            msg = json.loads(msg)
            model = Mail()
            # "ty":类型(0 个人 2 全服 3 联远商ID)
            model.title = msg.get("t", "")
            model.content = msg.get("m", "")
            if msg["rw"]:
                model.bonus_content = json.dumps(msg["rw"][0]["act"])
            model.type = msg["ty"]
            model.server_ids = str(server_id)
            model.channel_id = cha_id
            # model.player_id = json.dumps(player_ids) if player_ids else ""
            model.player_id = player_ids if player_ids else ''
            model.Applicant = str(request.admin.id)
            model.create_time = datetime.datetime.now()
            model.status = 0
            model.save(using='write')
            _r['code'] = 0
            err_msg = "成功保存"
            cur.close()
            con.commit()
            con.close()

        except Exception, e:
            traceback.print_exc()
            err_msg = trace_msg()
        _r['msg'] = err_msg
        return HttpResponse(json.dumps(_r))
Example #24
0
def server_make(request):
    list_group = Group.objects.using('read').all()
    # folderPath = os.path.abspath(os.path.join(STATIC_ROOT, 'server'))
    folderPath = os.path.abspath(os.path.join(STATIC_PATH, 'server'))
    _folderPath = os.path.abspath(
        os.path.join(STATIC_ROOT, 'client', 'static', 'server'))
    if not os.path.exists(folderPath):
        os.mkdir(folderPath)
    #     # clear old file
    # for file_item in os.listdir(folderPath):
    #     try:
    #         itemsrc = os.path.join(folderPath, file_item)
    #         if os.path.isfile(itemsrc):
    #             os.remove(itemsrc)
    #     except:
    #         pass

    list_server = Server.get_server_list()

    serverList = []
    for item in list_server:
        mongo_port = 27017
        db_address = ''
        if item.log_db_config != '':
            try:
                db_config = json.loads(item.log_db_config)
            except:
                continue
            mongo_port = int(db_config.get('mongo_port', '') or 27017)
            db_address = db_config.get('db_addr', item.game_addr)

        if None != item.report_url and '' != item.report_url:
            item.report_url = item.report_url.replace('http://', '')
            item.report_url = item.report_url.replace('/', '')

        name = item.name
        game_addr = item.game_addr
        game_addr = game_addr.replace('"', '\\"')
        name = name.replace('"', '\\"')
        # item_json = u'{"id":%d,"name":"%s","alias":"%s","address":"%s","db_address": "%s","gate_port":%d,"db_port":%d,"status":%d,"battle_report_url":"%s"}' % (
        #     item.id, name, item.alias, game_addr, db_address, item.game_port, mongo_port, item.status, item.report_url)
        item_json = u'{"id":%d,"name":"%s","alias":"%s","address":"%s","db_address": "%s","gate_port":%d,"db_port":%d,"status":%d}' % (
            item.id, name, item.alias, game_addr, db_address, item.game_port,
            mongo_port, item.status)
        try:
            json.loads(item_json)
        except Exception, ex:
            print ex, item_json
            return render_to_response('feedback.html',
                                      {"err_msg": "服务器ID:%s配置错误" % name})
        serverList.append(item_json)
Example #25
0
def log_syncdb_do(request,server_id=0):
    '''同步数据库
    '''
    server_id = server_id or int(request.REQUEST.get('sid', '0'))
    is_ajax = request.is_ajax() or request.REQUEST.get('ajax','')
    err_msg = ''
    _r = {"code":1,"content":[]}
    sync_status = {}

    try:
        if server_id:
            is_center = False
            the_server = Server.objects.get(id=server_id)
            the_server.create_base_table()                          #创建数据库,创建player表,创建log基表
            conn = the_server.mysql_conn()
        else:
            is_center = True
            conn = Server.get_conn(0)
        
        table_status = {"tol_num":0,
                       "sync_num":0,
                       "already_num":0
                       }
        
        index_status = copy.deepcopy(table_status)
        
        status = LogDefine.Status.CENTER if is_center else LogDefine.Status.NORMAL
        cur = conn.cursor()
        log_defs = LogDefine.objects.filter(status=status)
        for log_def in log_defs:
            table_status["tol_num"] += 1
            create_tabls_sql = log_def.get_create_table_sql()
            try:
                cur.execute(create_tabls_sql) #同步表
                table_status["sync_num"] += 1
            except MySQLdb.Warning,e:
                table_status["already_num"] += 1
                
            for create_index_sql in log_def.get_create_index_sqls() : #同步索引
                index_status["tol_num"] += 1
                #print create_index_sql
                try:
                    cur.execute(create_index_sql)
                    index_status["sync_num"] += 1
                except MySQLdb.OperationalError,e:
                    index_status["already_num"] += 1  
                except:
                    err_msg = trace_msg()  
                    print trace_msg()  
Example #26
0
def table_info(request):
    
    log_id = int(request.GET.get('log_id', '0'))
    server_id = int(request.GET.get('server_id', '0'))
    
    if 0 == server_id:
        server_id = int(request.POST.get('server_id', '0'))
    
    log_list = []
    if 0 == server_id:
        log_list = LogDefine.objects.filter(status = LogDefine.Status.CENTER).all()
    else:
        log_list = LogDefine.objects.filter(status = LogDefine.Status.NORMAL).all()
    
    server_list = Server.get_server_list()
    
    parg = {}
    
    if 0 != log_id and -1 != server_id:
        if 0 == LogDefine.objects.filter(id = log_id).count():
            return HttpResponse('请选择日志表')
        
        log_def = None
        for item in log_list:
            if item.id == log_id:
                log_def = item
        
        if None == log_def:
            return HttpResponse('请选择日志表')
        
        query_sql = 'show index from log_%s' %  log_def.key
        conn = conn_switch(server_id)
        cursor = conn.cursor()
        cursor.execute(query_sql) 
        list_data = cursor.fetchall()
        #raise Exception, query_sql
        conn.close()
        
        parg['log_def'] = log_def
        parg['list_data'] = list_data
    
    parg['log_id'] = log_id
    parg['log_list'] = log_list
    parg['server_list'] = server_list
    parg['server_id'] = server_id
    
    return render_to_response('log/table_info.html', parg)
Example #27
0
 def get_player_list(self, server_id, count):
     # 获取分服玩家列表信息
     if not server_id or not count:
         return
     try:
         conn = Server.get_conn(server_id)
         sql = '''
         select last_ip,c,link_key from(select last_ip,count(0) c ,link_key from player_%d group by last_ip) a where c >= %d and last_ip != ""
         ''' % (server_id, count)
         cursor = conn.cursor()
         cursor.execute(sql)
         result = cursor.fetchall()
         print result
         return result
     except BaseException as e:
         print "%s 链接数据库时发生错误!%s" % (server_id, e)
         return []
Example #28
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))

        # 列表包str格式,str空格切割
        if not data:
            return self.write(dict(code=-1, msg='不能为空'))

        # 判断下格式长度
        with DBContext('w', None, True) as session:
            for i in data:
                if i:
                    server_info = i.split(' ')
                    ins_log.read_log(
                        'info', 'MultiServer:{server_info}'.format(
                            server_info=server_info))
                    if len(server_info) != 4:
                        return self.write(dict(code=-2, msg='格式错误'))
                    hostname = server_info[0]
                    ip = server_info[1]
                    port = server_info[2]
                    admin_user = server_info[3]
                    if not check_ip(ip):
                        return self.write(dict(code=-1, msg="IP格式不正确"))

                    if not type(port) is int and int(port) >= 65535:
                        return self.write(dict(code=-1, msg="端口格式不正确"))

                    exist_id = session.query(
                        Server.id).filter(Server.hostname == hostname).first()
                    exist_ip = session.query(
                        Server.id).filter(Server.ip == ip).first()
                    if exist_id or exist_ip:
                        return self.write(
                            dict(code=-2,
                                 msg='IP:{ip}/Hostname:{hostname}已经存在,不要重复记录'.
                                 format(ip=ip, hostname=hostname)))

                    new_server = Server(hostname=hostname,
                                        ip=ip,
                                        port=int(port),
                                        admin_user=admin_user)
                    session.add(new_server)
            session.commit()

        return self.write(dict(code=0, msg='批量添加成功'))
Example #29
0
def log_syncdb_data(request, server_id=0):
    '''同步创建表
    '''
    err_msg = ''
    
    server_id = int(server_id)
    if 0 == server_id:
        server_id = int(request.GET.get('server_id', 0))
    
    if 0 == server_id:
        server_id = int(request.POST.get('server_id', 0))
    
    if server_id > 0:
        try:
            conn = Server.get_conn(server_id)
        except:
            err_msg = '数据库链接出错!'
    else:
        conn = connection
        
    if err_msg != '':
        parg = {}
        parg["err_msg"] = err_msg
        return render_to_response('feedback.html', parg)
    cursor = conn.cursor()
    is_reload = True
    page_size = 50
    try:
        #sql = 'select id,log_result from log_create_role where log_channel=0 limit %d'%page_size
        sql = 'select id,log_result from log_create_role where log_channel=0 and log_result>0 limit %d' % page_size
        print(sql)
        cursor.execute(sql)
        list_record = cursor.fetchall()
        if len(list_record) < 10:
            is_reload = False
        for item in list_record:
            the_user = User.objects.get(id=item[1])
            if the_user.channel_key != '':
                the_channel = Channel.objects.get(channel_key=the_user.channel_key)
                sql = 'update log_create_role set log_channel=%d where id=%d' % (the_channel.id, int(item[0]))
                print(sql)
                cursor.execute(sql)
    except Exception, e:
        print('syncdb data has error', e)
Example #30
0
 def handle(self, *args, **kwargs):
     while True:
         keep_connections()
         base_sql = self.get_base_sql()
         servers = Server.objects.all()
         base_info = self.get_base_info()
         for s in servers:
             try:
                 game_data = {}
                 if not s.json_data:
                     conn = Server.get_conn(s.id)
                     for logName,logSql in base_sql.iteritems():
                         print '-'*40
                         print s.id,logSql
                         print '-'*40
                         cursor = conn.cursor()
                         cursor.execute(logSql)
                         result = cursor.fetchone()
                         game_data[logName] = float(result[0]) if result[0] else ""
                         cursor.close()
                         s.game_data = json.dumps(game_data)
                         s.save(using="write")
                 else:
                     master_id = json.loads('{%s}' % s.json_data)["master_server_id"]
                     server = Server.objects.get(id=master_id)
                     game_data = json.loads(server.game_data)
                     for field,value in base_info.iteritems():
                         if game_data.has_key(field):
                             if s.id not in game_data[field]:
                                 _ = game_data[field]
                                 _.append(unicode(s.id))
                                 game_data[field] = _
                         else:
                             game_data[field] = [str(s.id)]
                     server.game_data = json.dumps(game_data)
                     server.save(using="write")
             except BaseException as e:
                 print s.id,e
                 s.game_data = json.dumps({"top_power":"","avg_power":"","ten_power":"","avg_level":"","sub_server":[]})
                 s.save(using="write")
                 continue
         print u"现在时间:",datetime.datetime.now()
         time.sleep(6400)
Example #31
0
def check_player_channel(request):
    '''检查用户拥有的渠道是否和发送的玩家一致'''

    cha_list = list(request.admin.role.first().resource_ids.get('channel', ''))  # 用户拥有的渠道
    player = request.REQUEST.get("player", '')
    player_ids = eval(player)
    print player_ids
    if isinstance(player_ids, int):
        player_ids = [player_ids]
    try:
        vv = []

        for i in player_ids:
            server_id = i >> 20
            print i, server_id
            sql = "select channel_id from player_%s where player_id =%s" % (server_id, i)  #############分服获取当前渠道
            con = Server.get_conn(server_id)  #######连接分服的数据库
            cur = con.cursor()
            cur.execute(sql)
            res = cur.fetchall()
            print 'oooooooooooooo', cha_list, player, res[0][0], server_id, vv.__len__()
            if res[0][0] and int(res[0][0]) in cha_list:

                if vv.__len__() == 0:
                    vv.append(int(res[0][0]))
                else:
                    if int(res[0][0]) == vv[0]:
                        pass
                    else:
                        return HttpResponse(i)
            else:
                return HttpResponse(i)
            cur.close()
            con.close()
        return HttpResponse(0)

    except Exception, e:
        print e
        return HttpResponse(33)
    def create_center_platform_statistic_table(cls):

        #保存结果表
        platfrom_result_table_sql = '''CREATE TABLE IF NOT EXISTS `%s` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `log_type` int(11) NOT NULL,
  `log_user` int(11) DEFAULT NULL,
  `log_name` varchar(100) DEFAULT NULL,
  `log_server` int(11) DEFAULT NULL,
  `log_channel` int(11) DEFAULT NULL,
  `log_data` int(11) DEFAULT NULL,
  `log_result` int(11) DEFAULT NULL,
  `log_level` int(11) DEFAULT NULL,
  `log_time` datetime NOT NULL,
  `log_previous` varchar(200) DEFAULT NULL,
  `log_now` varchar(200) DEFAULT NULL,
  `log_tag` int(11) DEFAULT NULL,
  `f1` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`,`log_time`),
  KEY `log_platform_result_log_type` (`log_type`),
  KEY `log_platform_result_log_time` (`log_time`),
  KEY `log_platform_result_log_server` (`log_server`),
  KEY `log_platform_result_log_channel` (`log_channel`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 
 PARTITION BY RANGE (year(log_time)) 
 (
 PARTITION p201x VALUES LESS THAN (2010),
 PARTITION p2010 VALUES LESS THAN (2011),
 PARTITION p2011 VALUES LESS THAN (2012),
 PARTITION p2012 VALUES LESS THAN (2013),
 PARTITION p2013 VALUES LESS THAN (2014),
 PARTITION p2014 VALUES LESS THAN (2015),
 PARTITION p2015 VALUES LESS THAN (2016),
 PARTITION p2016 VALUES LESS THAN (2017),
 PARTITION p2017 VALUES LESS THAN (2018),
 PARTITION p2018 VALUES LESS THAN (2019),
 PARTITION p2019 VALUES LESS THAN (2020),
 PARTITION p202x VALUES LESS THAN (MAXVALUE)
 ) ''' % cls.result_table_name
        #保存结果临时表
        platfrom_result_tmp_table_sql = '''
CREATE TABLE IF NOT EXISTS `%s` (
  `log_type` int(11) NOT NULL,
  `log_user` int(11) DEFAULT NULL,
  `log_name` varchar(100) DEFAULT NULL,
  `log_server` int(11) DEFAULT NULL,
  `log_channel` int(11) DEFAULT NULL,
  `log_data` int(11) DEFAULT NULL,
  `log_result` int(11) DEFAULT NULL,
  `log_level` int(11) DEFAULT NULL,
  `log_time` datetime NOT NULL,
  `log_previous` varchar(200) DEFAULT NULL,
  `log_now` varchar(200) DEFAULT NULL,
  `log_tag` int(11) DEFAULT NULL,
  `f1` varchar(100) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8   
''' % cls.platfrom_result_tmp_table_name
        #获取记录日志表
        platfrom_result_log_table_sql = '''
CREATE TABLE IF NOT EXISTS `%s`  like log_0_new
    ''' % cls.platfrom_result_log_table_name

        #创建保存数据的表和临时表

        conn = Server.get_conn(0)
        cur = conn.cursor()
        try:
            cur.execute(platfrom_result_table_sql)
        except MySQLdb.Warning:
            pass
        try:
            cur.execute(platfrom_result_tmp_table_sql)
        except MySQLdb.Warning:
            pass
        try:
            cur.execute(platfrom_result_log_table_sql)
        except MySQLdb.Warning:
            pass
        conn.commit()
        conn.close()
Example #33
0
    def sync_cmdb(self):
        """
        写入CMDB
        :return:
        """

        server_list = self.get_server_info()
        if not server_list:
            ins_log.read_log('info', 'Not fount server info')
            return False
        with DBContext('w') as session:
            for server in server_list:
                ip = server.get('public_ip')
                instance_id = server.get('instance_id', 'Null')
                hostname = server.get('hostname', instance_id)
                if hostname == '' or not hostname:
                    hostname = instance_id
                region = server.get('region', 'Null')
                instance_type = server.get('instance_type', 'Null')
                instance_state = server.get('instance_state', 'Null')
                cpu = server.get('cpu', 'Null')
                cpu_cores = server.get('cpu_cores', 'Null')
                memory = server.get('memory', 'Null')
                disk = server.get('disk', 'Null')  # 阿里云接口里面好像没有disk信息
                os_type = server.get('os_type', 'Null')
                os_name = server.get('os_name', 'Null')
                os_kernel = server.get('os_kernel', 'Null')
                sn = server.get('sn', 'Null')

                exist_hostname = session.query(Server).filter(
                    Server.hostname == hostname).first()
                if exist_hostname:
                    session.query(Server).filter(
                        Server.hostname == hostname).update({
                            Server.ip:
                            ip,
                            Server.public_ip:
                            ip,
                            Server.idc:
                            self.account,
                            Server.region:
                            region,
                            Server.admin_user:
                            self.default_admin_user
                        })

                else:
                    if os_type == 'windows':
                        # windows机器不绑定管理用户,资产信息只是平台拿到的一些基础信息
                        new_windows_server = Server(ip=ip,
                                                    public_ip=ip,
                                                    hostname=hostname,
                                                    port=3389,
                                                    idc=self.account,
                                                    region=region,
                                                    state=self.state)
                        session.add(new_windows_server)

                    else:
                        # unix机器给默认绑定上管理用户,用于后续登陆机器拿详细资产使用的
                        new_server = Server(ip=ip,
                                            public_ip=ip,
                                            hostname=hostname,
                                            port=22,
                                            idc=self.account,
                                            region=region,
                                            state=self.state,
                                            admin_user=self.default_admin_user)
                        session.add(new_server)

                exist_ip = session.query(ServerDetail).filter(
                    ServerDetail.ip == ip).first()
                if exist_ip:
                    session.query(ServerDetail).filter(
                        ServerDetail.ip == ip).update({
                            ServerDetail.instance_id:
                            instance_id,
                            ServerDetail.instance_type:
                            instance_type,
                            ServerDetail.instance_state:
                            instance_state
                        })
                else:
                    if os_type == 'windows':

                        new_serve_detail = ServerDetail(
                            ip=ip,
                            instance_id=instance_id,
                            instance_type=instance_type,
                            instance_state=instance_state,
                            cpu=cpu,
                            cpu_cores=cpu_cores,
                            memory=memory,
                            os_type=os_name,
                            disk=disk,
                            os_kernel=os_kernel,
                            sn=sn)
                        session.add(new_serve_detail)

                    else:
                        new_serve_detail = ServerDetail(
                            ip=ip,
                            instance_id=instance_id,
                            instance_type=instance_type,
                            instance_state=instance_state,
                            cpu=cpu,
                            cpu_cores=cpu_cores,
                            memory=memory,
                            os_type=os_name,
                            disk=disk,
                            os_kernel=os_kernel,
                            sn=sn)
                        session.add(new_serve_detail)
            session.commit()