1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#!/usr/bin/python
# -*- coding: GBK -*-
#-------------------------------------------------------------------------------
#
#-------------------------------------------------------------------------------
#
 
#-------------------------------------------------------------------------------
#¼ì²é²¢¸üÐÂË÷Òý
#-------------------------------------------------------------------------------
 
from CollectionDefine import *
from Common import(mylog,)
DBConfig = __import__('Config.DBConfig')
import os
from DBCommon import (GlobalFunctions, error)
import pymongo
 
def ReadIndexInfo(indexInfoFile):
    indexInfoDict = {}
    if not os.path.isfile(indexInfoFile):
        mylog.info('%s not found!'%indexInfoFile)
        return indexInfoDict
    mylog.info('Reading index file %s...'%indexInfoFile)
    try:
        fileObj = open(indexInfoFile)
        indexInfo = fileObj.read()
    except IOError, e:
#        print "open file %s failed!%s"%(indexInfoFile, e)
        msg = error.formatMsg('fatal', error.ERROR_NO_164, 'Open %s exception %s'%(indexInfoFile, e))
        mylog.fatal(msg)
        return indexInfoDict
    finally:
        fileObj.close()
    mylog.info('Parsing index file %s...'%indexInfoFile)
    try:
        indexInfoDict = eval(indexInfo)
    except:
#        print 'file %s content eval error!'%indexInfoFile
        msg = error.formatMsg('fatal', error.ERROR_NO_165, 'file %s content eval error %s'%(indexInfoFile, e))
        mylog.fatal(msg)
        return indexInfoDict
 
    mylog.info('Read index file %s ok!'%indexInfoFile)
    return indexInfoDict
 
def CompareIndex(curIndexDict, expectIndexDict):
    #±È½Ïunique
    curUnique = curIndexDict.get('unique', None)
    expectUnique = expectIndexDict.get('unique', None)
    if curUnique is None:
        if expectUnique is None:
            pass
        elif expectUnique:
#            print '#debug 1'
            return False
        else:
            pass
    else:
        if expectUnique is None:
            if (not curUnique):
                return True
#            print '#debug 2'
            return False
        if curUnique and (not expectUnique):
#            print '#debug 3'
            return False
        if (not curUnique) and expectUnique:
#            print '#debug 4'
            return False
    #±È½Ïkeylist
    curKeyList = curIndexDict.get('key', None)
    expectKeyList = expectIndexDict.get('key', None)
    if curKeyList is None:
        if expectKeyList is None:
            pass
        else:
#            print '#debug 5'
            return False
    else:
        if expectKeyList is None:
#            print '#debug 6'
            return False
        else:
            for pair in curKeyList:
                if pair not in expectKeyList:
#                    print '#debug 7'
                    return False
            for pair in expectKeyList:
                if pair not in curKeyList:
#                    print '#debug 8'
                    return False
    return True
 
def CheckIndexes(db, colName, expectIndexInfo):
    col = db[colName]
#    print 'checking index info on %s...'%colName
    mylog.info('checking index info on %s...'%colName)
    '''¼ì²é±íÖÐÊÇ·ñÓжàÓàµÄË÷Òý'''
    indexDict = col.index_information()
    for k, v in indexDict.items():
        if k == '_id_':
            continue
        if k not in expectIndexInfo:
#            print 'unexpect index %s:%s found!'%(k,v)
            msg = error.formatMsg('fatal', error.ERROR_NO_166, 'unexpect index %s.%s found!'%(colName, k))
            mylog.fatal(msg)
            return False
        if not CompareIndex(v, expectIndexInfo[k]):
#            print '%s unmatched index found!'%colName
            msg = error.formatMsg('fatal', error.ERROR_NO_167, 'unmatched index %s.%s found! index in db:\r\n%s\r\n expect index:\r\n%s\r\n'%(colName, k, indexDict, expectIndexInfo))
            mylog.fatal(msg)
            return False
#    print 'check indx info on %s ok!'%colName
    mylog.info('check indx info on %s ok!'%colName)
    return True
 
def AddIndexes(db, colName, expectIndexes):
    '''Ìí¼ÓË÷Òý'''
    col = db[colName]
#    print 'adding index on %s'%colName
    mylog.info('adding index on %s'%colName)
    '''¸ø±íÌí¼ÓË÷Òý'''
    curIndexesDict = col.index_information()
    for k, v in expectIndexes.items():
        if k not in curIndexesDict:
            expectIndexInfo = expectIndexes[k]
            isUnique = expectIndexInfo.get('unique', False)
            try:
                col.create_index(expectIndexInfo['key'], name = k, unique = isUnique)
            except Exception,e:
#                print 'create index %s failed!'%(k)
                msg = error.formatMsg('fatal', error.ERROR_NO_168, 'create index %s.%s failed!%s'%(colName, k, e))
                mylog.fatal(msg)
                return False
#            print 'create index %s ok!'%k
            mylog.info('create index %s ok!'%k)
#    print 'add index on %s ok!'%colName
    mylog.info('add index on %s ok!'%colName)
    return True     
 
def CheckAndUpdateIndexOnDb(db, indexInfoFile):
    '''¶ÔÓÚË÷ÒýÎļþÖеÄÿ¸ö±í£¬Êý¾Ý¿âÖиñíÓеÄË÷ÒýÐÅÏ¢£¬Ë÷ÒýÎļþÖбØÐëÓв¢ÇÒÆ¥ÅäuniqueºÍ(key, direction)list'''
    indexInfoDict = ReadIndexInfo(indexInfoFile)
    for k, v in indexInfoDict.items():
        colName = k
        colIndexDict = v
        if not CheckIndexes(db, colName, colIndexDict):
            return False
        if not AddIndexes(db, colName, colIndexDict):
            return False
    return True
 
def CheckAndUpdateIndex():
    indexPath = os.path.join(GlobalFunctions.getAppPath(), 'index')
    
    usrDBCon = pymongo.Connection(DBConfig.USER_DB_IP, DBConfig.USER_DB_PORT, auto_start_request=False)
    if not GlobalFunctions.LoginMongoDB(DBConfig.userdb_user, DBConfig.userdb_pwd, connection = usrDBCon):
        msg = error.formatMsg('DeployError', error.ERROR_NO_13,
                              "LoginMongoDB failed:ip = %s, port = %s, user = %s,pwd = %s"%(DBConfig.USER_DB_IP,
                                                                                            DBConfig.USER_DB_PORT,
                                                                                            DBConfig.userdb_user,
                                                                                            DBConfig.userdb_pwd))
        mylog.DeployError(msg, True)
        return
    
    userDB = usrDBCon[DBConfig.USER_DB_NAME]
    userDBIndexFileName = os.path.join(indexPath, 'GameUser.txt')
    mylog.info('CheckAndUpdateIndexOnDb(%s, %s)...'%(DBConfig.USER_DB_NAME, userDBIndexFileName))
    if not CheckAndUpdateIndexOnDb(userDB, userDBIndexFileName):
        mylog.info('CheckAndUpdateIndexOnDb(%s, %s) failed!'%(DBConfig.USER_DB_NAME, userDBIndexFileName))
        return False
    mylog.info('CheckAndUpdateIndexOnDb(%s, %s) ok!'%(DBConfig.USER_DB_NAME, userDBIndexFileName))
    
    
    return True
 
def test():
    import pymongo
    
    con = pymongo.Connection()
    db = con.admin
    if not db.authenticate('sa', 'sa'):
        print 'auth failed!'
        os.system('pause')
        return
    
#    dbName = 'test'
#    con.drop_database(dbName)
#    db = con[dbName]
    
    if not CheckAndUpdateIndex():
        print '#info CheckAndUpdateIndex failed!'
    else:
        print '#info CheckAndUpdateIndex ok'
    os.system('pause')
 
if __name__ == "__main__":
    test()
    os.system('pause')