hch
2018-12-27 affca29e7500fc8e2e65cf15d19496a370f6329e
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#!/usr/bin/python
# -*- coding: GBK -*-
#
# @todo: 
#
# @author: Alee
# @date 2018-1-3 ÏÂÎç05:47:38
# @version 1.0
#
# @note: 
#
#---------------------------------------------------------------------
 
#ϵͳ
import os
import sys
import time
import datetime
from binary.PyNetwork import *
from threading import Thread
import logging
from DataReader import MapEventPointReader, ChinMapReader
 
import ConfigurationReader.RobotsConfigReader
import ConfigurationReader.ConfigIniReader 
from Robot.RobotMgr import *
 
import traceback
import base64
import pymongo
import datetime
 
 
ServerDBConfigPath1 = r"\Config\config.ini"
ServerDBConfigPath2 = r"\PyMongoDataServer.ini"
 
g_starttime = time.time()
 
BASE64_ENCODE_CNT = 3
XOR_KEY = 151
def GetEncodePsw(psw):
    ret = ""
    try:
        for i in range(BASE64_ENCODE_CNT):
            psw = base64.decodestring(psw)
    except:
 
        return False,ret
    
    for i in psw:
        ret += chr(ord(i)^XOR_KEY)
    return True, ret
 
TYPE_Time_Format = "%Y-%m-%d %H:%M:%S"
def GetDateTimeByStr(timeStr):
    timeStr = timeStr.strip().split(".")[0]
    try:
        return  datetime.datetime.strptime(timeStr, TYPE_Time_Format)
    except BaseException , e :
        return
 
    return
 
def ChangeTimeStrToNum(timeStr, timeFormat=TYPE_Time_Format):
    timeStr = datetime.datetime.strptime(timeStr, timeFormat).timetuple() 
    return int(time.mktime(timeStr)) 
 
 
# Êý¾Ý¿â¹ÜÀí
class MongoDBRobot():
    def __init__(self):
        self.user = ""
        self.pwd = ""
        self.dbIP = ""
        self.dbName = ""
        
        self.logdb = None
        self.interfaceDatadb = None
        self.userdb = None
        self.connection = None
    
        config =  ConfigurationReader.ConfigIniReader.GetConfig()
        
        self.PlayerOffTime = config.GetPlayerOffTime() #Íæ¼ÒÏÂÏßʱ³¤
        self.ServerDBConfigPath = config.GetServerDBConfigPath()    #Êý¾Ý¿â·¾¶
        self.InitDBCon()
        
        self.tokenList = []   # Êý¾Ý¿â»ñÈ¡£¬µÇ¼ȥ³ý
        self.maxPlayerCnt = config.GetMaxPlayerCnt()
        self.loginCnt = 0
        self.AccountSource = config.GetAccountSource()
        
    def InitDBCon(self):
        dbConfig = ConfigurationReader.ConfigIniReader.AppConfig(self.ServerDBConfigPath + ServerDBConfigPath1)
        dbConfig.SetSection( "auth" )
        self.user = dbConfig.GetValue("userdb_user")
        self.pwd = GetEncodePsw(dbConfig.GetValue("userdb_pwd"))[1]
        
        dbConfig2 = ConfigurationReader.ConfigIniReader.AppConfig(self.ServerDBConfigPath + ServerDBConfigPath2)
        dbConfig2.SetSection( "connect" )
        self.dbIP = dbConfig2.GetValue("USER_DB_IP")
        self.connection = pymongo.Connection(self.dbIP, 27017, auto_start_request=False)
        db = self.connection.admin
        if not db.authenticate(self.user, self.pwd):
            logging.error( "!!!InitDBCon error" )
            return
        
        self.userdb = self.connection[dbConfig2.GetValue("USER_DB_NAME")]
        
        logging.info("conn ok-----------")
        
    # 1.»ñÈ¡ÍÑ»ú¹ÒÍæ¼ÒÊý¾Ý--GameLog
    def GetTJGRobot(self):
        if self.AccountSource == 0:
            index = 0
            if len(sys.argv) == 2:
                index = sys.argv[1]
            clientMac = "abc"
            for i in xrange(self.maxPlayerCnt):
                accID = "ice%s_%s@yun@s1"%(index, i)
    
                account = ("123456789012345678901234567890ab", accID, clientMac, 1)
                if account not in self.tokenList:
                    self.tokenList.append(account)
        else:
            col = self.userdb["tagDSAccount"]
            account = None
            for rec in col.find(limit=self.maxPlayerCnt):
                account = ("123456789012345678901234567890ab", str(rec['ACCID']), 'anc', 1)
                if account not in self.tokenList:
                    self.tokenList.append(account)
            
            print account
        if self.tokenList:
            logging.info( "´ýµÇ¼µÄÍÑ»ú¹ÒÍæ¼Ò----:%s"%(len(self.tokenList)))
            #logging.debug( "´ýµÇ¼µÄÍÑ»ú¹ÒÍæ¼Ò----tokenList:%s"%(self.tokenList))
        
        return
    
    def GetTokenList(self):
        return self.tokenList
    
    def AddCrossRobotInfo(self, accID, IPList):
        account = ("123456789012345678901234567890ab", accID, "abc", 1, IPList)
        if account not in self.tokenList:
            self.tokenList.append(account)
    
    def RemoveToken(self, value):
        self.tokenList.remove(value)
    
class WorkerThread(Thread):
    def __init__(self, mgr, index ):
        Thread.__init__(self, None, None, "WorkerThreadPy%s"%index)
        self.mgr = mgr
        self.clsTick = 30
        self.lastClsTick = 0
 
    def run(self):
        logging.debug( "thread %s start" % self.getName() )
        while 1:
            try:
                #Ïß³Ì1 »ñÈ¡ÍÑ»ú¹ÒÍæ¼ÒÊý¾Ý£¬¼ÓÈëµ½robotmgr
                self.mgr.ThreadRun()
                time.sleep( 0.01 )   # Ãë       
                if time.time() - self.lastClsTick > self.clsTick:
                    os.system("cls")
                    self.lastClsTick = time.time()
                    
            except Exception, e:
                print str(e)
                print traceback.print_exc()
                logging.error( "WorkerThread: %s"%str(e) )
                logging.error( "WorkerThread: %s"%traceback.print_exc() )
            
    # 1.»ñÈ¡ÍÑ»ú¹ÒÍæ¼ÒÊý¾Ý--GameLog
    # 2.³õʼ»¯ÍÑ»ú¹ÒÍæ¼ÒµÄrobot¼ÓÈëmgr
    # 3.ÇëÇóÐÂtokenµÇ¼--InterfaceData
    # 4.µÇ¼ºóÔÚ0107loadmapok°üǰ·¢ËÍÍÑ»úµÇ¼ÏûÏ¢£¬ÓÃÓÚÇø·ÖÍæ¼ÒÕæÊµµÇ¼
    # 5.ÍÑ»ú¹ÒÍæ¼Ò·À³ÁÃÔÂß¼­ÐÞÕý£¬¸ù¾Ý4Ìõ¼þ
            
def StartApp( PyBaseRoot ):
    logging.info( "PyBaseRoot:%s" % PyBaseRoot )
    titleMark = 0
    if len(sys.argv) == 2:
        titleMark = sys.argv[1]
    
    os.system("title %s-Robot-%s"%(titleMark, datetime.datetime.today()))
    
    #¶ÁÈ¡¸÷ÖÖÅäÖã¨IP£¬¶Ë¿Ú£¬VERSION_NOµÈ£©
    ConfigurationReader.ConfigIniReader.ReadConfig( PyBaseRoot + "Configuration\\Config.ini" )
    config =  ConfigurationReader.ConfigIniReader.GetConfig()
    #logging.info( "ConfigData:%s" % str(config) )
    
    dbRobot = MongoDBRobot()
    
    #¶ÁÈ¡¸÷ÖÖÊý¾Ý£¨µØÍ¼£©, ÍÑ»ú¹ÒÖ±½Ó·ÉÐÐ
    #MapDataReader.ReadMapData( PyBaseRoot )
    #TransportDataReader.ReadTransportData( PyBaseRoot )
    MapEventPointReader.ReadMapEventPoint(PyBaseRoot)
    ChinMapReader.ReadChinMapData(PyBaseRoot)
    
    #³õʼ»¯ÍøÂ磨Asio£©
    asioMgr = CAsioMgr()
    ret = asioMgr.InitModule( config.GetVersionNo(), config.GetPackStartCount(),\
                              config.GetKeyString(), PyBaseRoot + config.GetSendKeyDictFilePath() )
    if not ret:
        logging.fatal( "Init PyNetwork failed." )
        return
    else:
        logging.debug( "Init PyNetwork success." )
     
    #´´½¨ÍøÂçÄ£¿é¹¤×÷Ị̈߳¬ÕâЩÏß³ÌÊýÁ¿²»Ò˹ý¶à£¬ÒÔÃâ³öÏÖ´óÁ¿¾ºÕù  
    #½¨Òéȡֵ·¶Î§ÔÚ nThreadsµ½2*nThreadsÖ®¼ä
    nThreads = asioMgr.GetProcessorNumber()
    logging.info( "Host has %d logic processor." % nThreads )
        
    IO_WORKER_THREAD_NUM = config.GetIOThreadNum()
    threadList = []
    logging.info( "Create %d IO Threads....." % IO_WORKER_THREAD_NUM )
    for i in range( IO_WORKER_THREAD_NUM ):
        th = WorkerThread( asioMgr, i )
        threadList.append( th )
        th.start()
 
    dbRobot.GetTJGRobot()
    #´´½¨RobotMgr£¬Ìṩ»úÆ÷ÈË×ÜÊý£¨´ËMgrÄÚ²¿»á´´½¨AIÏß³ÌÓÃÓÚ½øÐÐAI´¦Àí£©
    CreateRobotMgr( asioMgr, dbRobot)