Exemple #1
0
def player_block(request, server_id=0, player_id=0):
    player_id = int(player_id)
    server_id = int(server_id)

    if player_id == 0:
        player_id = int(request.GET.get('player_id', '0'))

    if server_id == 0:
        server_id = int(request.GET.get('server_id', '0'))

    if player_id > 0:
        try:
            conn = getConn(server_id)
            cursor = conn.cursor()
            if request.GET.get('is_lock', '1') == '1':
                the_status = -1
            else:
                the_status = 0

            query_sql = 'update player_%d set status=%d where player_id=%d' % (
                server_id, the_status, player_id)

            print(query_sql)
            cursor.execute(query_sql)
            cursor.close()
        except Exception, e:
            raise Exception, e
            print('lock user error:', e)
Exemple #2
0
def conn_switch(server_id):
    conn = None
    if 0 != server_id:
        conn = getConn(server_id)
    else:
        conn = connections['write']
    return conn
Exemple #3
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 = getConn(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
Exemple #4
0
def do_log_sync_index(request, server_id=0, log_id=0):
    server_id = int(server_id)
    log_id = int(log_id)
    if server_id == 0:
        server_id = int(request.GET.get('server_id', '0'))

    get_sql = int(request.GET.get('get_sql', request.POST.get('get_sql', 0)))
    save_path = ''
    if 1 == get_sql:
        sql_file_name = 'create_index_sql_%s.sql' % server_id
        gpc = GlobalPathCfg()
        save_path = gpc.get_create_index_save_path(sql_file_name)

    if log_id == 0:
        log_id = int(request.GET.get('log_id', '0'))

    error = "{code:1}"
    if log_id == 0:
        return HttpResponse(error)

    if 0 == LogDefine.objects.all().filter(id=log_id).count():
        return HttpResponse(error)

    conn = None
    if 0 == server_id:
        conn = connections['write']
    else:
        conn = getConn(server_id)
    model = LogDefine.objects.get(id=log_id)
    table_name = 'log_%s' % model.key
    index_list = get_table_index(conn, table_name)
    need_index_list = get_create_index_field_list(model.id)
    for field_def in need_index_list:
        has_index = False
        column_name = field_def[0]
        new_index_name = "index_%s_%s" % (table_name, column_name)
        for index in index_list:
            index_column_name = index[4]
            index_name = index[2]

            if pass_index_name(index_name):
                continue

            if index_column_name == column_name:
                #索引名字不一样删除索引
                has_index = True
                if new_index_name != index_name:
                    delete_index(conn, index_name, table_name, save_path)
                    has_index = False

        if not has_index:
            create_index(conn, new_index_name, table_name, column_name,
                         save_path)

    return HttpResponse("{code:0}")
Exemple #5
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 = getConn(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(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)
Exemple #6
0
def shutup_list(request, server_id=0):
    req_type = 503

    server_id = int(server_id)

    if server_id == 0:
        server_id = int(request.GET.get('server_id', '0'))

    net_id = request.GET.get('net_id', '-1')
    req_params = 'req_type=%d&server_id=%d&net_id=%s' % (req_type, server_id,
                                                         net_id)
    list_record = []
    try:
        result = http_post(game_server_url.GM_SERVER_URL,
                           req_params,
                           timeout_param=10)
        result = json.loads(result)
        print(game_server_url.GM_SERVER_URL, req_params, result)
        list_shutup = []
        if result['code'] == 0:
            list_shutup = result['content'][0]

        conn = getConn(server_id)
        cursor = conn.cursor()

        sql2 = 'select player_id,player_name,channel_id,user_type,link_key,login_num,mobile_key,last_time,create_time,status from player_%d where player_id in(%s)' % (
            server_id, ','.join(list_shutup))
        cursor.execute(sql2)

        list_tmp = cursor.fetchall()
        cursor.close()
        int_time = int(time.time())
        for item in list_tmp:
            #            print(item)
            item = list(item)
            item.append(list_shutup.get(str(item[0]), 0) - int_time)
            list_record.append(item)
    except Exception, e:
        pass
Exemple #7
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 = getConn(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)
Exemple #8
0
def query_view(request, query_id=0):
    query_id = int(query_id)

    if 0 == query_id:
        query_id = int(request.GET.get('id', request.POST.get('id', 0)))

    s_list = request.POST.getlist('s')
    if 0 == s_list.__len__():
        s_list = request.GET.getlist('s')

    page_num = int(request.GET.get('page_num', '1'))
    sdate = request.GET.get('sdate', '')
    edate = request.GET.get('edate', '')
    query_channel = request.GET.getlist('channel_id')
    group_id = int(request.GET.get('group_id', '0'))
    ajax = request.GET.get('ajax', False)
    exprot = int(request.GET.get('exprot', '0'))
    close_export = int(request.GET.get('close_export', '0'))
    clear_export_old_file = int(request.GET.get('clear_export_old_file', '0'))
    is_post_back = request.GET.get('post_back', False)
    exprot_file_key = request.GET.get('exprot_file_key', '')
    exprot_file_key = exprot_file_key.strip()
    more_serv_exprot = False
    if exprot_file_key != '':
        more_serv_exprot = True
    begin_exec_time = datetime.datetime.now()
    page_size = 50
    mc = MemcachedUtil()
    if exprot > 0:
        page_size = 500

    list_group = []
    usm = UserStateManager(request)
    the_user = usm.get_the_user()
    if query_id > 0:
        the_query = log_cache.get_query(query_id, mc)

    log_define = log_cache.get_logDefine(the_query.log_type, mc)

    #是否在中央服务器的查询
    is_centerQuery = False

    if log.the_log_in_center(log_define):  #check_user
        is_centerQuery = True
        is_select_server = False
    else:
        is_centerQuery = False
        is_select_server = True

    has_sql = False
    if the_query.sql != '':
        has_sql = True

    if not has_sql or -1 != the_query.sql.find('{{server_id}}'):
        is_select_server = True

    list_query = log_cache.get_query_list_by_logType(the_query.log_type, mc)
    if is_select_server:
        list_group = center_cache.get_group_list()

    if group_id != 0 and usm.current_userRole_is_root():
        list_server = center_cache.get_server_list(group_id, mc)
    else:
        if usm.current_userRole_is_root():
            list_server = center_cache.get_server_list(mc_util=mc)
        else:
            list_server = center_cache.get_user_server_list(the_user)

    #取出字段定义
    list_field = log_cache.get_fielddef_list_by_logType(the_query.log_type, mc)

    server_id = int(request.GET.get('server_id', '0'))
    if is_centerQuery and s_list.__len__() == 0:
        s_list = [str(item.id) for item in list_server]
        if not usm.current_userRole_is_root() and s_list.__len__() == 0:
            return HttpResponse(u"非法操作")
    elif server_id == 0 and len(list_server) > 0:
        server_id = list_server[0].id
        if server_id == 0:
            return HttpResponse(u"非法操作")

    if usm.current_userRole_is_root():
        list_channel = center_cache.get_channel_list(mc)
    else:
        list_channel = center_cache.get_user_channel_list(the_user, mc)

    #是否在页面上显示查询channel
    allowChannel = False

    if query_channel.__len__() == 0 and not usm.current_userRole_is_root():
        query_channel = []
        for item in list_channel:
            query_channel.append(str(item.id))

    if (not has_sql and list_channel.__len__() > 0) or (
            -1 != the_query.sql.find('{{qchannel')):
        allowChannel = True

    for item1 in list_channel:
        if query_channel.__len__() > 0:
            if str(item1.id) in query_channel:
                item1.is_show = 1
        else:
            item1.is_show = 0

    field_value = request.GET.get('field_value', '')
    field_value = filter_inject_sql(field_value)
    field_id = int(request.GET.get('field_id', '0'))

    if has_sql:
        field_value = request.GET.getlist('field_value')

    err_msg = ''

    pager_str = 'limit %s,%s' % ((page_num - 1) * page_size, page_size)

    fields = the_query.select.split(',')

    query_date = ''

    now = datetime.datetime.now()

    if not is_post_back:  #如果第一次进入该页面默认时间范围是昨天数据
        if sdate == '':
            sdate = (now -
                     datetime.timedelta(days=1)).strftime('%Y-%m-%d 00:00:00')

        if edate == '':
            edate = now.strftime('%Y-%m-%d 00:00:00')

    if not has_sql or the_query.sql.find('{{keyword}}') != -1:
        is_search = True
    else:
        is_search = False

    has_sdate = True
    has_edate = True

    if the_query.sql != '':
        if -1 == the_query.sql.find('{{sdate}}'):
            has_sdate = False

        if -1 == the_query.sql.find('{{edate}}'):
            has_edate = False

        if -1 != the_query.sql.find('{{qdate}}'):
            has_sdate = True
            has_edate = True

        if -1 == the_query.sql.find('{{qchannel'):
            allowChannel = False

    keywords = []
    lost_param = False
    if has_sql:
        sql = the_query.sql
        r_keyword_name = '(@keywords.+)'
        keyword_name_ary = re.findall(r_keyword_name, sql, re.I)

        if keyword_name_ary.__len__() != 0:
            keyword_name = keyword_name_ary[0]
            names_str = keyword_name.split(':')[1]
            names = names_str.split(',')
            for i in range(names.__len__()):
                name = names[i]
                value = ''
                if field_value.__len__() > i:
                    value = field_value[i]
                keywords.append({"name": name, "value": value})
            the_query.sql = re.sub(keyword_name, '', sql, re.I)
        else:
            k_len = the_query.sql.lower().count('{{keyword}}')
            for i in range(k_len):
                value = ''
                if field_value.__len__() > i:
                    value = field_value[i]
                if value == '':
                    lost_param = True
                keywords.append({"name": '输入框%s' % i, "value": value})

    #print keywords.__len__()
    list_data = []
    total_record = 0
    parg = {}
    parg['keywords'] = keywords
    parg['has_sql'] = has_sql
    parg['is_centerQuery'] = is_centerQuery
    parg['has_sdate'] = has_sdate
    parg['has_edate'] = has_edate
    parg["allowChannel"] = allowChannel
    parg["the_query"] = the_query
    parg["usm"] = usm
    parg["list_query"] = list_query
    parg["is_select_server"] = is_select_server
    parg["list_group"] = list_group
    parg["list_server"] = list_server
    parg["list_channel"] = list_channel
    parg["s_list"] = s_list
    parg["server_id"] = server_id
    parg["query_id"] = query_id
    parg["is_search"] = is_search
    parg["group_id"] = group_id
    parg["field_id"] = field_id
    parg["field_value"] = field_value
    parg["list_field"] = list_field
    parg["sdate"] = sdate
    parg["edate"] = edate
    parg["fields"] = fields

    parg["page_num"] = page_num
    parg["page_size"] = page_size
    parg["total_record"] = total_record

    if not is_post_back and not ajax:  #如果没有点击查询按钮并不是ajax提交则不查询数据(第一次进入页面不查询数据)    ——zhenwei  2012-10-22
        return render_to_response('log/query_view.html', parg)

    if is_select_server and not is_centerQuery:
        if server_id > 0:
            try:
                conn = getConn(server_id)
            except:
                err_msg = '数据库链接出错!'
    else:
        conn = connections['read']

    if err_msg != '':
        return render_to_response('feedback.html', locals())

    try:
        if sdate != '':
            sdate = datetime.datetime.strptime(
                sdate, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
            query_date = ' a.log_time>=\'%s\'' % sdate
        if edate != '':
            if query_date != '':
                query_date += ' and '
            edate = datetime.datetime.strptime(
                edate, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
            query_date += ' a.log_time<=\'%s\'' % edate
    except:
        sdate = ''
        edate = ''

    #是否有channel 查询条件
    channel_condition = query_channel.__len__() > 0
    query_key = ''
    if not has_sql:

        query_field = the_query.select
        query_where = the_query.where
        query_order = the_query.order
        query_group = the_query.group

        field_name = ''
        for field_item in list_field:
            query_field = query_field.replace(field_item.name,
                                              field_item.field_name)
            query_where = query_where.replace(field_item.name,
                                              field_item.field_name)
            query_order = query_order.replace(field_item.name,
                                              field_item.field_name)
            query_group = query_group.replace(field_item.name,
                                              field_item.field_name)
            if field_id == field_item.id:
                field_name = field_item.field_name

        #处理字段值查询
        if field_name != '':
            the_values = ValueDefine.objects.filter(field_id=field_id,
                                                    value=field_value)
            if len(the_values) > 0:
                field_value = the_values[0].value_id
            if query_where != '':
                query_where += ' and '
            query_where += u'a.%s=\'%s\'' % (field_name, field_value)

        if query_date != '':
            if query_where != '':
                query_where += ' and '
            query_where += query_date

        if channel_condition:
            if query_where != '':
                query_where += ' and '
            query_where += 'a.log_channel in(%s)' % (','.join(query_channel))

        if query_where != '':
            query_where = 'where %s' % query_where

        if query_order != '':
            query_order = ' order by a.%s' % query_order

            if the_query.order_type == 1:
                query_order += ' desc'

        count_sql = 'select count(0) from log_%s a %s' % (log_define.key,
                                                          query_where)

        query_sql = 'select %s from log_%s a %s %s %s' % (
            query_field, log_define.key, query_where, query_order, pager_str)

        query_key = md5('%s_%s' % (query_sql, server_id))
        if exprot_file_key == '':
            exprot_file_key = md5('%s_%s' % (query_sql, server_id))
        #print(query_sql)
    else:

        query_sql = the_query.sql.replace('\r\n\t', ' ').replace('\r\n', ' ')

        if is_centerQuery and s_list.__len__() > 0:
            server_list_str = ' IN (%s) ' % (','.join(s_list))
            query_sql = re.sub('=[\s]*{{server_id}}', server_list_str,
                               query_sql)
        elif server_id > 0:
            query_sql = query_sql.replace('{{server_id}}', str(server_id))

        if query_date != '':
            query_sql = query_sql.replace("{{qdate}}", query_date)
            query_sql = query_sql.replace('{{sdate}}', '%s' % sdate).replace(
                '{{edate}}',
                '%s' % edate)  #支持自定对非log表的日期支持   -zhenwei 2012-10-25
        else:
            query_sql = query_sql.replace('and {{qdate}}',
                                          '').replace('where {{qdate}}', '')
            query_sql = query_sql.replace(
                '\'{{sdate}}\'', 'DATE(\'2001-01-01\')').replace(
                    '\'{{edate}}\'',
                    'NOW()')  #支持自定对非log表的日期支持   -zhenwei 2012-10-25

        if lost_param:
            err_msg = '请输入查询条件'
            return render_to_response('feedback.html', {"err_msg": err_msg})


#        if field_value != '':
#            query_sql = query_sql.replace("{{keyword}}", field_value)
#        else:
#            if -1 != query_sql.find('{{keyword}}'):
#                err_msg = '请输入查询条件'
#                return render_to_response('feedback.html', {"err_msg":err_msg})

        if channel_condition:
            query_sql = query_sql.replace(
                '{{qchannel}}',
                'log_channel in(%s)' % (','.join(query_channel)))
        else:
            query_sql = query_sql.replace('and {{qchannel}}',
                                          '').replace('where {{qchannel}}', '')

        if channel_condition:
            query_sql = query_sql.replace(
                '{{qchannela}}',
                'a.log_channel in(%s)' % (','.join(query_channel)))
        else:
            query_sql = query_sql.replace('and {{qchannela}}',
                                          '').replace('where {{qchannela}}',
                                                      '')

        if channel_condition:
            query_sql = query_sql.replace(
                '{{qchannelb}}',
                'b.log_channel in(%s)' % (','.join(query_channel)))
        else:
            query_sql = query_sql.replace('and {{qchannelb}}',
                                          '').replace('where {{qchannelb}}',
                                                      '')

        if channel_condition:
            query_sql = query_sql.replace(
                '{{qchannelid}}',
                'channel_id in (%s)' % (','.join(query_channel)))

        query_sql = filter_keyword(query_sql, field_value)

        count_sql = 'select count(0) from (%s) newTable' % query_sql

        if exprot_file_key == '':
            exprot_file_key = md5('%s_%s' % (query_sql, server_id))

        if query_sql.find('limit') == -1:
            query_sql = '%s %s' % (query_sql, pager_str)

        query_key = md5('%s_%s' % (query_sql, server_id))

    parg['has_sdate'] = has_sdate
    parg['has_edate'] = has_edate

    print count_sql
    print query_sql
    #raise Exception, count_sql
    #desc = cursor.description
    cursor = conn.cursor()
    # update log_create_role
    channelKey_id_dic = {}

    query_memcache = mc
    if the_query.cache_validate != None and 0 != the_query.cache_validate:
        query_memcache = MemcachedUtil(valid_date=the_query.cache_validate)

    for item1 in list_channel:
        channelKey_id_dic[item1.key] = int(item1.id)
    try:
        count_query_key = md5('%s_%s' % (count_sql, server_id))
        total_record = log_cache.get_query_count(count_sql, count_query_key,
                                                 cursor, query_memcache)
    except Exception, e:
        raise Exception, e
        print('query_view error:', e)
        return render_to_response('feedback.html', {"err_msg": "查询数据时出错"})
Exemple #9
0
def backup_execute(request, backup_id=0):
    msg = ''
    from GameManage.settings import STATIC_ROOT
    backup_type = int(request.GET.get("backup_type", "0"))
    page_num = int(request.GET.get('page_num', '1'))
    all_server = int(request.GET.get('all_server', '0'))
    task_id = int(request.GET.get("task_id", "0"))
    page_size = 20
    query_date = ''
    sdate = request.GET.get('sdate', '')
    edate = request.GET.get('edate', '')

    date_type = int(request.GET.get('date_type', '0'))
    ajax = request.GET.get('ajax', False)
    exprot = int(request.GET.get('exprot', '0'))
    close_export = int(request.GET.get('close_export', '0'))
    clear_export_old_file = int(request.GET.get('clear_export_old_file', '0'))
    usm = UserStateManager(request)
    server_id = int(request.GET.get('server_id', '0'))

    is_select_server = False

    if exprot > 0:
        page_size = 500
    is_post_back = request.GET.get('post_back', False)
    now = datetime.datetime.now()
    #    if not is_post_back:#如果第一次进入该页面默认时间范围是昨天数据
    #        if sdate == '':
    #            sdate = (now - datetime.timedelta(days=1)).strftime('%Y-%m-%d 00:00:00')
    #        if edate == '':
    #            edate = now.strftime('%Y-%m-%d 00:00:00')
    pager_str = 'limit %s,%s' % ((page_num - 1) * page_size, page_size)
    err_msg = ''

    backup_id = int(backup_id)
    request_url = ''
    if backup_id > 0:
        the_query = Backup.objects.get(id=backup_id)
        request_url = the_query.sql
    if the_query.field_name.find('feiyin') != -1:
        fields = the_query.field_name
    else:
        fields = the_query.field_name.split(',')
    file_str = the_query.backup_format
    if the_query.auto_exec_interval > 0:
        sleep_time = the_query.auto_exec_interval
    else:
        sleep_time = 10
    query_sql = the_query.sql.replace('\r\n\t', ' ').replace('\r\n', ' ')

    if the_query.sql == '' or -1 != the_query.sql.find('{{server_id}}'):
        is_select_server = True

    query = []
    query.append(
        " `status` not in (-1,0) AND `log_db_config` NOT REGEXP '\"fy\"'")
    list_server = Server.objects.using('read').extra(
        where=[''.join(query)]).order_by('id')
    if server_id == 0 and len(list_server) > 0:
        server_id = list_server[0].id

    if server_id > 0:  #支持服务器条件
        query_sql = query_sql.replace('{{server_id}}', str(server_id))
        query_sql = query_sql.replace('{{log_server}}', str(server_id))

    #date_type
    # 1 daily
    # 2 monthly
    # 3 first
    # 4 closed
    date_name = ''
    day_format = ''
    next_time = 0
    file_str_list = file_str.split('___')
    log_type = file_str_list[len(file_str_list) - 1]

    start_date = the_query.start_date
    end_date = the_query.end_date

    if date_type == 1:
        date_name = 'daily'
        if start_date != '' and start_date != None and start_date != 'None' and task_id > 0:
            sdate = start_date.strftime('%Y-%m-%d 00:00:00')
            edate = start_date.strftime('%Y-%m-%d 23:59:59')
            day_format = start_date.strftime("%Y%m%d")
        else:
            sdate = (now -
                     datetime.timedelta(days=1)).strftime('%Y-%m-%d 00:00:00')
            edate = (now -
                     datetime.timedelta(days=1)).strftime('%Y-%m-%d 23:59:59')
            day_format = (now - datetime.timedelta(days=1)).strftime("%Y%m%d")
        next_time = 86400
    elif date_type == 2:
        date_name = 'monthly'
        today = datetime.date.today()

        current_month_days = calendar.monthrange(today.year, today.month)[1]
        if today.month > 1:
            last_year = today.year
            last_month = today.month - 1
            last_month_days = calendar.monthrange(today.year,
                                                  today.month - 1)[1]
        else:
            last_year = today.year - 1
            last_month = 12
            last_month_days = 31
        sdate = today.strftime('%s-%s-01 00:00:00' % (last_year, last_month))
        edate = today.strftime('%s-%s-%s 23:59:59' %
                               (last_year, last_month, last_month_days))
        day_format = today.strftime("%Y%m01")
        next_time = 86400 * current_month_days
    elif date_type == 3:
        date_name = 'first'
        sdate = '1970-01-01 00:00:00'
        if start_date != '' and start_date != None and start_date != 'None' and task_id > 0:
            edate = start_date.strftime('%Y-%m-%d 23:59:59')
            day_format = start_date.strftime('%Y%m%d')
        else:
            edate = (now -
                     datetime.timedelta(days=1)).strftime('%Y-%m-%d 23:59:59')
            day_format = (now - datetime.timedelta(days=1)).strftime('%Y%m%d')
        next_time = -86400
    elif date_type == 4:
        date_name = 'closed'
        sdate = '1970-01-01 00:00:00'
        edate = (now -
                 datetime.timedelta(days=1)).strftime('%Y-%m-%d 23:59:59')
        day_format = (now - datetime.timedelta(days=1)).strftime('%Y%m%d')
        next_time = -86400
    elif date_type == 5:
        if sdate == '' or edate == '':
            return HttpResponse(json.dumps({"msg": "时间不能为空"}))
        sdate = sdate
        edate = edate

    if query_date == '':
        query_sql = query_sql.replace("{{qdate}}", query_date)
        query_sql = query_sql.replace('{{sdate}}', '%s' % sdate).replace(
            '{{edate}}', '%s' % edate)  #支持自定对非log表的日期支持   -zhenwei 2012-10-25
    count_sql = 'select count(0) from (%s) newTable' % query_sql
    if query_sql.find('limit') == -1:
        query_sql = '%s %s' % (query_sql, pager_str)

    if the_query.remark != '':
        is_select_server = False

    next_url = 'http://127.0.0.1:8080' + request.META[
        'PATH_INFO'] + '?' + request.META['QUERY_STRING']
    if is_select_server:
        if server_id > 0:
            try:
                conn = getConn(server_id)
            except:
                err_msg = '数据库链接出错!'
                if backup_type == 1:
                    #save_log('query_view error', next_url,log_type)
                    if Backup().get_server_id(server_id, list_server) != False:
                        next_url = re.sub(r"page_num=\d+", "page_num=1",
                                          next_url)
                        next_url = re.sub(
                            r"server_id=\d+", "server_id=%d" %
                            Backup().get_server_id(server_id, list_server),
                            next_url)
                        taskresult = SleepTask(sleep_time, next_url)
                    else:
                        request_url = ''
                        try:
                            if task_id > 0:
                                the_task = TaskDefine.objects.get(id=task_id)
                                if start_date.strftime(
                                        '%Y-%m-%d'
                                ) < the_task.trigger_date.strftime(
                                        '%Y-%m-%d') and start_date.strftime(
                                            '%Y-%m-%d') < end_date.strftime(
                                                '%Y-%m-%d'
                                            ) and end_date.strftime(
                                                '%Y-%m-%d'
                                            ) < the_task.trigger_date.strftime(
                                                '%Y-%m-%d'):
                                    next_time = int(time.time()) - int(
                                        time.mktime(
                                            the_task.trigger_date.timetuple())
                                    ) + sleep_time + 15
                                    the_query.start_date = (
                                        start_date + datetime.timedelta(days=1)
                                    ).strftime('%Y-%m-%d')
                                else:
                                    the_query.start_date = (
                                        the_task.trigger_date
                                    ).strftime('%Y-%m-%d')
                                    the_query.end_date = (
                                        the_task.trigger_date
                                    ).strftime('%Y-%m-%d')
                                the_query.save()

                                the_task.counter = 0
                                the_task.request_url = the_task.source_url
                                the_task.save()

                                request_url = the_task.request_url
                        except Exception, e:
                            print 'task error', e
                            msg = 'task error %s' % e
                        save_log(
                            '\nall_is_finish!\n next_time %s\n request_url %s\n'
                            % (next_time, request_url), '%s' % msg, log_type)

                        taskresult = IntervalTask(next_time)
                    return task_response(taskresult)
Exemple #10
0
def player_list(request, server_id=0):
    page_size = 30
    page_num = int(request.GET.get("page_num", "1"))
    is_block = int(request.GET.get("block", 0))
    group_id = int(request.GET.get("group_id", 0))
    post_back = int(request.GET.get('post_back', '0'))

    list_group = center_cache.get_group_list()

    if (page_num < 1):
        page_num = 1

    usm = UserStateManager(request)
    the_user = usm.get_the_user()

    list_channel = center_cache.get_channel_list()

    itemChannelList = {}
    for item in list_channel:
        itemChannelList[item.id] = item.name

    list_group_server = []
    if group_id != 0:
        list_group_server = center_cache.get_group_server_list(group_id)

    if usm.current_userRole_is_root():
        list_server = center_cache.get_server_list()
    else:
        list_server = center_cache.get_user_server_list(the_user)

    tmp_list_server = []
    if 0 != list_group_server.__len__():
        for item in list_group_server:
            if list_server.__contains__(item):
                tmp_list_server.append(item)
        list_server = tmp_list_server

    itemServerList = {}
    for item in list_server:
        itemServerList[item.id] = item.name

    player_key = request.GET.get('key', '')
    key_type = request.GET.get('key_type', '0')
    user_type = int(request.GET.get('user_type', '-1'))
    channel_id = int(request.session.get('channelId', '0'))

    server_id = int(request.GET.get("server_id", "0"))

    if server_id <= 0:
        server_id = int(request.session.get("serverId", "0"))
    if server_id <= 0 and len(list_server) > 0:
        server_id = list_server[0].id

    #账号状态
    status_condition = 0
    if is_block == 1:
        status_condition = -1

    total_record = 0
    player_list = []
    player_list1 = []

    if 0 != post_back and server_id > 0:
        conn = getConn(server_id)
        cursor = conn.cursor()

        query = []
        query.append("status=%d" % status_condition)
        if channel_id > 0:
            query.append('channel_id=%d' % channel_id)

        if player_key != "":
            if key_type == '0':
                query.append('player_id=\'%s\'' % player_key)
            elif key_type == '1':
                query.append('player_name like \'%s%%\'' %
                             player_key.encode('utf-8'))
            elif key_type == '2':
                query.append('link_key=\'%s\'' % player_key)
            elif key_type == '3':
                query.append('mobile_key=\'%s\'' % player_key)
        if user_type > -1:
            query.append('user_type=%d' % player_key)

        if not usm.current_userRole_is_root():
            channel_list = center_cache.get_user_channel_list(the_user)
            channel_id_list_query = ' channel_id in (%s) ' % ','.join(
                [str(item.id) for item in channel_list])
            query.append(channel_id_list_query)

        if len(query) > 0:
            sql1 = 'select count(1) from player_%d where %s' % (
                server_id, ' and '.join(query))
            sql2 = 'select player_id,player_name,channel_id,user_type,link_key,login_num,mobile_key,last_time,create_time,status from player_%d where %s order by id desc limit %d,%d' % (
                server_id, ' and '.join(query),
                (page_num - 1) * page_size, page_num * page_size)
        else:
            sql1 = 'select count(1) from player_%d' % server_id
            sql2 = 'select player_id,player_name,channel_id,user_type,link_key,login_num,mobile_key,last_time,create_time,status from player_%d order by id desc limit %d,%d' % (
                server_id, (page_num - 1) * page_size, page_num * page_size)

        print(sql1, sql2)
        cursor.execute(sql1)
        count_list = cursor.fetchone()
        total_record = int(count_list[0])
        if total_record > 0:
            cursor.execute(sql2)
            player_list1 = cursor.fetchall()
        user_type_name = {
            0: '游爱',
            1: '当乐',
            2: 'UC',
            3: '91',
            4: '云游',
            5: '飞流',
            6: '乐逗',
            8: '小虎',
            9: '4399',
            10: 'facebook',
            11: 'qq'
        }
        for item in player_list1:
            item = list(item)

            item[2] = itemChannelList.get(int(item[2]), item[2])

            item[3] = user_type_name.get(int(item[3]), item[3])

            player_list.append(item)
        cursor.close()
    parg = {}
    parg["server_id"] = server_id
    parg["list_group"] = list_group
    parg["list_server"] = list_server
    parg["player_key"] = player_key
    parg["server_id"] = server_id
    parg["player_list"] = player_list
    parg["is_block"] = is_block
    parg["usm"] = usm

    parg["page_num"] = page_num
    parg["page_size"] = page_size
    parg["total_record"] = total_record

    return render_to_response('player/player_list.html', parg)
Exemple #11
0
def player_silver_detail(request):
    server_id = request.POST.get("server_id", "")
    query_incoming = request.POST.getlist("incoming_type")
    query_outcoming = request.POST.getlist("outcoming_type")
    sdate = request.POST.get("sdate", "")
    edate = request.POST.get("edate", "")
    page_num = int(request.GET.get('page_num', '1'))
    user_id = request.POST.get("user_id", "")
    user_name = request.POST.get("user_name", "")
    err_msg = ''
    page_size = 30

    list_server = center_cache.get_server_list()

    if server_id == "":
        server_id = "0"
    server_id = int(server_id)

    if server_id < 1 and len(list_server) > 0:
        server_id = list_server[0].id

    if user_id == "":
        user_id = "0"
    user_id = int(user_id)

    query_where = " and 1=1"
    try:
        if sdate != "":
            sdate = datetime.datetime.strptime(
                sdate, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M:%S")
            query_where += " and a.log_time>='%s'" % sdate
        if edate != "":
            edate = datetime.datetime.strptime(
                edate, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M:%S")
            query_where += " and a.log_time<='%s'" % edate
    except:
        sdate = ""
        edate = ""

    logDefine = LogDefine.objects.get(key='silver')

    fieldDefine = FieldDefine.objects.get(log_type=logDefine.id, name=u'操作项目')
    incoming_list = ValueDefine.objects.filter(field_id=fieldDefine.id,
                                               value_id__lt=10000)
    silverType_Dic = {}
    for inItem in incoming_list:
        silverType_Dic[inItem.value_id] = inItem.value
        if len(query_incoming) > 0:
            if str(inItem.value_id) in query_incoming:
                inItem.is_show = True
            else:
                inItem.is_show = False
        else:
            if request.method == "GET":
                inItem.is_show = True
            else:
                inItem.is_show = False

    outcoming_list = ValueDefine.objects.filter(field_id=fieldDefine.id,
                                                value_id__gte=10000)
    for outItem in outcoming_list:
        silverType_Dic[outItem.value_id] = outItem.value
        if len(query_outcoming) > 0:
            if str(outItem.value_id) in query_outcoming:
                outItem.is_show = True
            else:
                outItem.is_show = False
        else:
            if request.method == "GET":
                outItem.is_show = True
            else:
                outItem.is_show = False

    query_type = []
    if len(query_incoming) > 0:
        query_type = query_type + query_incoming

    if len(query_outcoming) > 0:
        query_type = query_type + query_outcoming
#
#    if len(query_type)>0:
#        query_where+=" and log_data in (%s)"(','.join(query_type))

    server_in = ""
    if len(query_type) > 0:
        server_in = "("
        for typeItem in query_type:
            if server_in == "(":
                server_in += "%s" % typeItem
            else:
                server_in += ",%s" % typeItem
        server_in += ")"

    if server_in != "" and len(query_type) != (len(incoming_list) +
                                               len(outcoming_list)):
        query_where += " and a.log_data in %s" % server_in


#    if user_name!="":
#        query_where+=" and b.f1=%s"%user_name

    if server_id > 0:
        try:
            conn = getConn(server_id)
        except:
            err_msg = '数据库链接出错!'

    cursor = conn.cursor()

    if user_id < 1:
        if user_name != "":
            query_role_sql = "SELECT log_user FROM log_create_role WHERE f1='%s'" % user_name
            cursor.execute(query_role_sql)
            role_object = cursor.fetchone()
            if role_object != None:
                user_id = int(role_object[0])

    if user_id > 0:
        query_where += " and a.log_user=%s" % user_id

    query_sql = "SELECT a.log_user,b.f1,a.log_time,a.log_result,a.f2,a.log_data,a.f3 FROM log_silver a,log_create_role b WHERE a.log_user=b.log_user %s order by a.id desc" % query_where
    query_count_sql = "SELECT count(1) FROM log_silver a where 1=1 %s" % query_where

    cursor.execute(query_count_sql)
    total_record = int(cursor.fetchone()[0])

    pager_str = 'limit %s,%s' % ((page_num - 1) * page_size, page_size)
    query_sql = query_sql + ' ' + pager_str

    print query_count_sql
    print query_sql

    cursor.execute(query_sql)
    silver_list_temp = cursor.fetchall()

    fieldDefine_f3 = FieldDefine.objects.get(log_type=logDefine.id, name=u'备注')
    valueDefine_f3_list = ValueDefine.objects.filter(
        field_id=fieldDefine_f3.id)
    f3_dic = {}
    for vdItem in valueDefine_f3_list:
        f3_dic[vdItem.value_id] = vdItem.value

    silver_list = []
    for silverItem in silver_list_temp:
        role_name = ""
        if silverItem[5] != "":
            role_name = silverType_Dic[int(silverItem[5])]
        detail_name = ""
        if silverItem[6] != "":
            detail_name = f3_dic[int(silverItem[6])]
        silver_list.append((silverItem[0], silverItem[1], silverItem[2],
                            silverItem[3], silverItem[4], silverItem[5],
                            role_name, silverItem[6], detail_name))

    cursor.close()

    if user_id < 1:
        user_id = ""

    parg = {}
    parg["list_server"] = list_server
    parg["server_id"] = server_id
    parg["incoming_list"] = incoming_list
    parg["outcoming_list"] = outcoming_list
    parg["sdate"] = sdate
    parg["edate"] = edate
    parg["user_id"] = user_id
    parg["user_name"] = user_name
    parg["silver_list"] = silver_list

    parg["page_num"] = page_num
    parg["page_size"] = page_size
    parg["total_record"] = total_record

    return render_to_response('player/player_silver_detail.html', parg)
Exemple #12
0
def update_pay_action_channel(request):

    sdate = request.GET.get('sdate', request.POST.get('sdate', ''))
    edate = request.GET.get('edate', request.POST.get('edate', ''))

    sid = int(request.GET.get('sid', request.POST.get('sid', 0)))
    eid = int(request.GET.get('eid', request.POST.get('eid', 0)))
    page_size = 100

    if eid - sid > page_size:
        eid = sid + page_size

    where_sql = ' (channel_id = 0 OR channel_id IS NULL) AND pay_status >= 4 AND pay_amount > 0 '

    if '' != sdate and '' != edate:
        sdate = datetime.datetime.strptime(sdate,
                                           '%Y-%m-%d').strftime('%Y-%m-%d')
        edate = datetime.datetime.strptime(edate,
                                           '%Y-%m-%d').strftime('%Y-%m-%d')
        where_sql = where_sql + " AND last_time BETWEEN '%s' AND '%s' " % (
            sdate, edate)

    center_con = connections['write']
    center_cur = center_con.cursor()
    pargs = {"status": 1}

    if 0 == sid or 0 == eid:
        count_sql = 'SELECT MIN(id), MAX(id) FROM pay_action  WHERE %s ' % where_sql
        center_cur.execute(count_sql)
        result_item = center_cur.fetchone()
        min_id = 0
        max_id = 0
        if None != result_item:
            if None != result_item[0] and None != result_item[0]:
                min_id, max_id = int(result_item[0]), int(result_item[1])
        pargs["min_id"] = min_id
        pargs["max_id"] = max_id
        pargs["page_size"] = page_size

        sid = min_id
        eid = sid + page_size

    sql = 'SELECT id,server_id,channel_key,pay_user FROM pay_action WHERE %s AND id BETWEEN %s AND %s ' % (
        where_sql, sid, eid)

    center_cur.execute(sql)
    list_data = center_cur.fetchall()

    channel_list = get_channel_list()
    for item in list_data:
        item_id = item[0]
        server_id = item[1]
        channel_key = item[2]
        pay_user = item[3]

        channel_id = 0

        if '' != channel_key and None != channel_key:

            for channel_item in channel_list:
                if channel_item.key == channel_key:
                    channel_id = channel_item.id

        if 0 == channel_id:
            con = None
            cur = None
            try:
                con = getConn(server_id)
                cur = con.cursor()
                tmp_sql = 'SELECT channel_id FROM player_%s WHERE player_id=%s' % (
                    server_id, pay_user)
                cur.execute(tmp_sql)
                list_player_result = cur.fetchall()
                if 0 < list_player_result.__len__():
                    channel_id = list_player_result[0][0]
            except:
                continue
            finally:
                if None != cur:
                    cur.close()

                if None != con:
                    con.close()

        if 0 != channel_id:
            update_sql = 'UPDATE pay_action SET channel_id=%s WHERE id=%s '
            center_cur.execute(update_sql % (channel_id, item_id))

    sid = eid + 1
    eid = sid + page_size

    pargs["sid"] = sid
    pargs["eid"] = eid
    pargs["status"] = 0
    return HttpResponse(json.dumps(pargs))
Exemple #13
0
    ip = OperateLogManager.get_request_ipAddress(request)
    try:
        OperateLogManager.save_operate_log(
            the_user.id,
            '添加订单, pay_channel:%s server_id:%s player_id:%s  amount:%s' %
            (pay_channel, server_id, player_id, amount), '/pay/add', ip, 0)
    except Exception, ex:
        print ex
    finally:
        print 'add order, pay_channel:%s server_id:%s player_id:%s  amount:%s ' % (
            pay_channel, server_id, player_id, amount)

    channel_id = 0
    msg = ''
    try:
        conn = getConn(server_id)
        cur = conn.cursor()
        sql = 'SELECT channel_id FROM player_%s where player_id = %s' % (
            server_id, player_id)
        print sql
        cur.execute(sql)
        result_list = cur.fetchall()
        if 0 < result_list.__len__():
            channel_id = result_list[0][0]
        else:
            msg = '用户不存在'
    except Exception, ex:
        print ex
        msg = '用户不存在'

    the_pay_channel = PayChannel.objects.get(id=pay_channel)
Exemple #14
0
def user_convert(request, server_id=0):
    server_id = int(server_id)
    err_msg = ''
    if server_id > 0:
        try:
            conn = getConn(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()

    start_pos = int(request.GET.get('pos', 0))
    if start_pos == 0:
        query_sql = 'select id from log_create_role where log_user=(select max(player_id) from player_%d)' % (
            server_id, )
        cursor.execute(query_sql)
        last_player_id = cursor.fetchone()
        if last_player_id != None:
            start_pos = int(last_player_id[0])

    sql = 'select log_user,log_result,f1,log_time,id from log_create_role where id>%d order by id limit 100' % start_pos
    cursor.execute(sql)
    list_record = cursor.fetchall()
    for item in list_record:
        try:
            #先判断存在与否
            sql = 'select count(0) from player_%d where player_id=%d' % (
                server_id, item[0])
            cursor.execute(sql)
            count_list = cursor.fetchone()
            total_record = int(count_list[0])

            if total_record == 0:
                the_user = User.objects.using('read').get(id=item[1])
                if the_user.user_type == 0:
                    link_key = the_user.id
                else:
                    link_key = the_user.link_key
                channel_id = 0
                try:
                    the_channel = Channel.objects.using('read').get(
                        key=the_user.channel_key)
                    channel_id = the_channel.id
                except:
                    pass
                try:
                    sql = '''insert into player_%d(player_id,player_name,user_type,link_key,channel_id,create_time,last_ip,last_time,login_num,status,mobile_key)
                            values(%s,"%s",%s,"%s",%s,"%s","%s","%s",0,0,"%s")''' % (
                        server_id, item[0], item[2].replace(
                            '\\', '\\\\'), the_user.user_type, link_key,
                        channel_id, item[3], the_user.last_ip,
                        the_user.last_time, the_user.mobile_key)
                    cursor.execute(sql)
                except Exception, e:
                    print('convert user has error', e, item[0])
        except Exception, e:
            print('convert user has error', e, item[0])
        start_pos = item[4]