ConnectionRepository.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. from pandac.PandaModules import *
  2. from direct.task import Task
  3. from direct.directnotify import DirectNotifyGlobal
  4. from direct.distributed.DoInterestManager import DoInterestManager
  5. from direct.distributed.DoCollectionManager import DoCollectionManager
  6. from PyDatagram import PyDatagram
  7. from PyDatagramIterator import PyDatagramIterator
  8. import types
  9. import imp
  10. class ConnectionRepository(
  11. DoInterestManager, DoCollectionManager, CConnectionRepository):
  12. """
  13. This is a base class for things that know how to establish a
  14. connection (and exchange datagrams) with a gameserver. This
  15. includes ClientRepository and AIRepository.
  16. """
  17. notify = DirectNotifyGlobal.directNotify.newCategory("ConnectionRepository")
  18. taskPriority = -30
  19. CM_HTTP=0
  20. CM_NET=1
  21. CM_NATIVE=2
  22. def __init__(self, connectMethod, config, hasOwnerView=False):
  23. assert self.notify.debugCall()
  24. # let the C connection repository know whether we're supporting
  25. # 'owner' views of distributed objects (i.e. 'receives ownrecv',
  26. # 'I own this object and have a separate view of it regardless of
  27. # where it currently is located')
  28. CConnectionRepository.__init__(self, hasOwnerView)
  29. # DoInterestManager.__init__ relies on CConnectionRepository being
  30. # initialized
  31. DoInterestManager.__init__(self)
  32. DoCollectionManager.__init__(self)
  33. self.setPythonRepository(self)
  34. self.config = config
  35. if self.config.GetBool('verbose-repository'):
  36. self.setVerbose(1)
  37. # Set this to 'http' to establish a connection to the server
  38. # using the HTTPClient interface, which ultimately uses the
  39. # OpenSSL socket library (even though SSL is not involved).
  40. # This is not as robust a socket library as NET's, but the
  41. # HTTPClient interface does a good job of negotiating the
  42. # connection over an HTTP proxy if one is in use.
  43. #
  44. # Set it to 'net' to use Panda's net interface
  45. # (e.g. QueuedConnectionManager, etc.) to establish the
  46. # connection. This is a higher-level layer build on top of
  47. # the low-level "native net" library. There is no support for
  48. # proxies. This is a good, general choice.
  49. #
  50. # Set it to 'native' to use Panda's low-level native net
  51. # interface directly. This is much faster than either http or
  52. # net for high-bandwidth (e.g. server) applications, but it
  53. # doesn't support the simulated delay via the start_delay()
  54. # call.
  55. #
  56. # Set it to 'default' to use an appropriate interface
  57. # according to the type of ConnectionRepository we are
  58. # creating.
  59. userConnectMethod = self.config.GetString('connect-method', 'default')
  60. if userConnectMethod == 'http':
  61. connectMethod = self.CM_HTTP
  62. elif userConnectMethod == 'net':
  63. connectMethod = self.CM_NET
  64. elif userConnectMethod == 'native':
  65. connectMethod = self.CM_NATIVE
  66. self.connectMethod = connectMethod
  67. if self.connectMethod == self.CM_HTTP:
  68. self.notify.info("Using connect method 'http'")
  69. elif self.connectMethod == self.CM_NET:
  70. self.notify.info("Using connect method 'net'")
  71. elif self.connectMethod == self.CM_NATIVE:
  72. self.notify.info("Using connect method 'native'")
  73. self.connectHttp = None
  74. self.http = None
  75. # This DatagramIterator is constructed once, and then re-used
  76. # each time we read a datagram.
  77. self.private__di = PyDatagramIterator()
  78. self.recorder = None
  79. # This is the string that is appended to symbols read from the
  80. # DC file. The AIRepository will redefine this to 'AI'.
  81. self.dcSuffix = ''
  82. self._serverAddress = ''
  83. if self.config.GetBool('want-debug-leak', 1):
  84. import gc
  85. gc.set_debug(gc.DEBUG_SAVEALL)
  86. def generateGlobalObject(self, doId, dcname, values=None):
  87. def applyFieldValues(distObj, dclass, values):
  88. for i in range(dclass.getNumInheritedFields()):
  89. field = dclass.getInheritedField(i)
  90. if field.asMolecularField() == None:
  91. value = values.get(field.getName(), None)
  92. if value is None and field.isRequired():
  93. # Gee, this could be better. What would really be
  94. # nicer is to get value from field.getDefaultValue
  95. # or similar, but that returns a binary string, not
  96. # a python tuple, like the following does. If you
  97. # want to change something better, please go ahead.
  98. packer = DCPacker()
  99. packer.beginPack(field)
  100. packer.packDefaultValue()
  101. packer.endPack()
  102. unpacker = DCPacker()
  103. unpacker.setUnpackData(packer.getString())
  104. unpacker.beginUnpack(field)
  105. value = unpacker.unpackObject()
  106. unpacker.endUnpack()
  107. if value is not None:
  108. function = getattr(distObj, field.getName())
  109. if function is not None:
  110. function(*value)
  111. else:
  112. self.notify.error("\n\n\nNot able to find %s.%s"%(
  113. distObj.__class__.__name__, field.getName()))
  114. # Look up the dclass
  115. dclass = self.dclassesByName.get(dcname+self.dcSuffix)
  116. if dclass is None:
  117. print "\n\n\nNeed to define", dcname+self.dcSuffix
  118. dclass = self.dclassesByName.get(dcname+'AI')
  119. if dclass is None:
  120. dclass = self.dclassesByName.get(dcname)
  121. # Create a new distributed object, and put it in the dictionary
  122. #distObj = self.generateWithRequiredFields(dclass, doId, di)
  123. # Construct a new one
  124. classDef = dclass.getClassDef()
  125. if classDef == None:
  126. self.notify.error("Could not create an undefined %s object."%(
  127. dclass.getName()))
  128. distObj = classDef(self)
  129. distObj.dclass = dclass
  130. # Assign it an Id
  131. distObj.doId = doId
  132. # Put the new do in the dictionary
  133. self.doId2do[doId] = distObj
  134. # Update the required fields
  135. distObj.generateInit() # Only called when constructed
  136. distObj.generate()
  137. if values is not None:
  138. applyFieldValues(distObj, dclass, values)
  139. distObj.announceGenerate()
  140. distObj.parentId = 0
  141. distObj.zoneId = 0
  142. # updateRequiredFields calls announceGenerate
  143. return distObj
  144. def readDCFile(self, dcFileNames = None):
  145. """
  146. Reads in the dc files listed in dcFileNames, or if
  147. dcFileNames is None, reads in all of the dc files listed in
  148. the Configrc file.
  149. """
  150. dcFile = self.getDcFile()
  151. dcFile.clear()
  152. self.dclassesByName = {}
  153. self.dclassesByNumber = {}
  154. self.hashVal = 0
  155. if isinstance(dcFileNames, types.StringTypes):
  156. # If we were given a single string, make it a list.
  157. dcFileNames = [dcFileNames]
  158. dcImports = {}
  159. if dcFileNames == None:
  160. readResult = dcFile.readAll()
  161. if not readResult:
  162. self.notify.error("Could not read dc file.")
  163. else:
  164. for dcFileName in dcFileNames:
  165. readResult = dcFile.read(Filename(dcFileName))
  166. if not readResult:
  167. self.notify.error("Could not read dc file: %s" % (dcFileName))
  168. if not dcFile.allObjectsValid():
  169. names = []
  170. for i in range(dcFile.getNumTypedefs()):
  171. td = dcFile.getTypedef(i)
  172. if td.isBogusTypedef():
  173. names.append(td.getName())
  174. nameList = ', '.join(names)
  175. self.notify.error("Undefined types in DC file: " + nameList)
  176. self.hashVal = dcFile.getHash()
  177. # Now import all of the modules required by the DC file.
  178. for n in range(dcFile.getNumImportModules()):
  179. moduleName = dcFile.getImportModule(n)[:]
  180. # Maybe the module name is represented as "moduleName/AI".
  181. suffix = moduleName.split('/')
  182. moduleName = suffix[0]
  183. suffix=suffix[1:]
  184. if self.dcSuffix in suffix:
  185. moduleName += self.dcSuffix
  186. elif self.dcSuffix == 'UD' and 'AI' in suffix: #HACK:
  187. moduleName += 'AI'
  188. importSymbols = []
  189. for i in range(dcFile.getNumImportSymbols(n)):
  190. symbolName = dcFile.getImportSymbol(n, i)
  191. # Maybe the symbol name is represented as "symbolName/AI".
  192. suffix = symbolName.split('/')
  193. symbolName = suffix[0]
  194. suffix=suffix[1:]
  195. if self.dcSuffix in suffix:
  196. symbolName += self.dcSuffix
  197. elif self.dcSuffix == 'UD' and 'AI' in suffix: #HACK:
  198. symbolName += 'AI'
  199. importSymbols.append(symbolName)
  200. self.importModule(dcImports, moduleName, importSymbols)
  201. # Now get the class definition for the classes named in the DC
  202. # file.
  203. for i in range(dcFile.getNumClasses()):
  204. dclass = dcFile.getClass(i)
  205. number = dclass.getNumber()
  206. className = dclass.getName() + self.dcSuffix
  207. # Does the class have a definition defined in the newly
  208. # imported namespace?
  209. classDef = dcImports.get(className)
  210. if classDef is None and self.dcSuffix == 'UD': #HACK:
  211. className = dclass.getName() + 'AI'
  212. classDef = dcImports.get(className)
  213. # Also try it without the dcSuffix.
  214. if classDef == None:
  215. className = dclass.getName()
  216. classDef = dcImports.get(className)
  217. if classDef is None:
  218. self.notify.debug("No class definition for %s." % (className))
  219. else:
  220. if type(classDef) == types.ModuleType:
  221. if not hasattr(classDef, className):
  222. self.notify.error("Module %s does not define class %s." % (className, className))
  223. classDef = getattr(classDef, className)
  224. if type(classDef) != types.ClassType and type(classDef) != types.TypeType:
  225. self.notify.error("Symbol %s is not a class name." % (className))
  226. else:
  227. dclass.setClassDef(classDef)
  228. self.dclassesByName[className] = dclass
  229. if number >= 0:
  230. self.dclassesByNumber[number] = dclass
  231. # Owner Views
  232. if self.hasOwnerView():
  233. ownerDcSuffix = self.dcSuffix + 'OV'
  234. # dict of class names (without 'OV') that have owner views
  235. ownerImportSymbols = {}
  236. # Now import all of the modules required by the DC file.
  237. for n in range(dcFile.getNumImportModules()):
  238. moduleName = dcFile.getImportModule(n)
  239. # Maybe the module name is represented as "moduleName/AI".
  240. suffix = moduleName.split('/')
  241. moduleName = suffix[0]
  242. suffix=suffix[1:]
  243. if ownerDcSuffix in suffix:
  244. moduleName = moduleName + ownerDcSuffix
  245. importSymbols = []
  246. for i in range(dcFile.getNumImportSymbols(n)):
  247. symbolName = dcFile.getImportSymbol(n, i)
  248. # Check for the OV suffix
  249. suffix = symbolName.split('/')
  250. symbolName = suffix[0]
  251. suffix=suffix[1:]
  252. if ownerDcSuffix in suffix:
  253. symbolName += ownerDcSuffix
  254. importSymbols.append(symbolName)
  255. ownerImportSymbols[symbolName] = None
  256. self.importModule(dcImports, moduleName, importSymbols)
  257. # Now get the class definition for the owner classes named
  258. # in the DC file.
  259. for i in range(dcFile.getNumClasses()):
  260. dclass = dcFile.getClass(i)
  261. if ((dclass.getName()+ownerDcSuffix) in ownerImportSymbols):
  262. number = dclass.getNumber()
  263. className = dclass.getName() + ownerDcSuffix
  264. # Does the class have a definition defined in the newly
  265. # imported namespace?
  266. classDef = dcImports.get(className)
  267. if classDef is None:
  268. self.notify.error("No class definition for %s." % className)
  269. else:
  270. if type(classDef) == types.ModuleType:
  271. if not hasattr(classDef, className):
  272. self.notify.error("Module %s does not define class %s." % (className, className))
  273. classDef = getattr(classDef, className)
  274. dclass.setOwnerClassDef(classDef)
  275. self.dclassesByName[className] = dclass
  276. def importModule(self, dcImports, moduleName, importSymbols):
  277. """
  278. Imports the indicated moduleName and all of its symbols
  279. into the current namespace. This more-or-less reimplements
  280. the Python import command.
  281. """
  282. module = __import__(moduleName, globals(), locals(), importSymbols)
  283. if importSymbols:
  284. # "from moduleName import symbolName, symbolName, ..."
  285. # Copy just the named symbols into the dictionary.
  286. if importSymbols == ['*']:
  287. # "from moduleName import *"
  288. if hasattr(module, "__all__"):
  289. importSymbols = module.__all__
  290. else:
  291. importSymbols = module.__dict__.keys()
  292. for symbolName in importSymbols:
  293. if hasattr(module, symbolName):
  294. dcImports[symbolName] = getattr(module, symbolName)
  295. else:
  296. raise StandardError, 'Symbol %s not defined in module %s.' % (symbolName, moduleName)
  297. else:
  298. # "import moduleName"
  299. # Copy the root module name into the dictionary.
  300. # Follow the dotted chain down to the actual module.
  301. components = moduleName.split('.')
  302. dcImports[components[0]] = module
  303. def getServerAddress(self):
  304. return self._serverAddress
  305. def connect(self, serverList,
  306. successCallback = None, successArgs = [],
  307. failureCallback = None, failureArgs = []):
  308. """
  309. Attempts to establish a connection to the server. May return
  310. before the connection is established. The two callbacks
  311. represent the two functions to call (and their arguments) on
  312. success or failure, respectively. The failure callback also
  313. gets one additional parameter, which will be passed in first:
  314. the return status code giving reason for failure, if it is
  315. known.
  316. """
  317. ## if self.recorder and self.recorder.isPlaying():
  318. ## # If we have a recorder and it's already in playback mode,
  319. ## # don't actually attempt to connect to a gameserver since
  320. ## # we don't need to. Just let it play back the data.
  321. ## self.notify.info("Not connecting to gameserver; using playback data instead.")
  322. ## self.connectHttp = 1
  323. ## self.tcpConn = SocketStreamRecorder()
  324. ## self.recorder.addRecorder('gameserver', self.tcpConn)
  325. ## self.startReaderPollTask()
  326. ## if successCallback:
  327. ## successCallback(*successArgs)
  328. ## return
  329. hasProxy = 0
  330. if self.checkHttp():
  331. proxies = self.http.getProxiesForUrl(serverList[0])
  332. hasProxy = (proxies != 'DIRECT')
  333. if hasProxy:
  334. self.notify.info("Connecting to gameserver via proxy list: %s" % (proxies))
  335. else:
  336. self.notify.info("Connecting to gameserver directly (no proxy).")
  337. #Redefine the connection to http or net in the default case
  338. self.bootedIndex = None
  339. self.bootedText = None
  340. if self.connectMethod == self.CM_HTTP:
  341. # In the HTTP case, we can't just iterate through the list
  342. # of servers, because each server attempt requires
  343. # spawning a request and then coming back later to check
  344. # the success or failure. Instead, we start the ball
  345. # rolling by calling the connect callback, which will call
  346. # itself repeatedly until we establish a connection (or
  347. # run out of servers).
  348. ch = self.http.makeChannel(0)
  349. self.httpConnectCallback(
  350. ch, serverList, 0,
  351. successCallback, successArgs,
  352. failureCallback, failureArgs)
  353. elif self.connectMethod == self.CM_NET or (not hasattr(self,"connectNative")):
  354. # Try each of the servers in turn.
  355. for url in serverList:
  356. self.notify.info("Connecting to %s via NET interface." % (url.cStr()))
  357. if self.tryConnectNet(url):
  358. self.startReaderPollTask()
  359. if successCallback:
  360. successCallback(*successArgs)
  361. return
  362. # Failed to connect.
  363. if failureCallback:
  364. failureCallback(0, '', *failureArgs)
  365. elif self.connectMethod == self.CM_NATIVE:
  366. for url in serverList:
  367. self.notify.info("Connecting to %s via Native interface." % (url.cStr()))
  368. if self.connectNative(url):
  369. self.startReaderPollTask()
  370. if successCallback:
  371. successCallback(*successArgs)
  372. return
  373. # Failed to connect.
  374. if failureCallback:
  375. failureCallback(0, '', *failureArgs)
  376. else:
  377. print "uh oh, we aren't using one of the tri-state CM variables"
  378. failureCallback(0, '', *failureArgs)
  379. def disconnect(self):
  380. """
  381. Closes the previously-established connection.
  382. """
  383. self.notify.info("Closing connection to server.")
  384. self._serverAddress = ''
  385. CConnectionRepository.disconnect(self)
  386. self.stopReaderPollTask()
  387. def httpConnectCallback(self, ch, serverList, serverIndex,
  388. successCallback, successArgs,
  389. failureCallback, failureArgs):
  390. if ch.isConnectionReady():
  391. self.setConnectionHttp(ch)
  392. self._serverAddress = serverList[serverIndex-1]
  393. ## if self.recorder:
  394. ## # If we have a recorder, we wrap the connect inside a
  395. ## # SocketStreamRecorder, which will trap incoming data
  396. ## # when the recorder is set to record mode. (It will
  397. ## # also play back data when the recorder is in playback
  398. ## # mode, but in that case we never get this far in the
  399. ## # code, since we just create an empty
  400. ## # SocketStreamRecorder without actually connecting to
  401. ## # the gameserver.)
  402. ## stream = SocketStreamRecorder(self.tcpConn, 1)
  403. ## self.recorder.addRecorder('gameserver', stream)
  404. ## # In this case, we pass ownership of the original
  405. ## # connection to the SocketStreamRecorder object.
  406. ## self.tcpConn.userManagesMemory = 0
  407. ## self.tcpConn = stream
  408. self.startReaderPollTask()
  409. if successCallback:
  410. successCallback(*successArgs)
  411. elif serverIndex < len(serverList):
  412. # No connection yet, but keep trying.
  413. url = serverList[serverIndex]
  414. self.notify.info("Connecting to %s via HTTP interface." % (url.cStr()))
  415. ch.preserveStatus()
  416. ch.beginConnectTo(DocumentSpec(url))
  417. ch.spawnTask(name = 'connect-to-server',
  418. callback = self.httpConnectCallback,
  419. extraArgs = [ch, serverList, serverIndex + 1,
  420. successCallback, successArgs,
  421. failureCallback, failureArgs])
  422. else:
  423. # No more servers to try; we have to give up now.
  424. if failureCallback:
  425. failureCallback(ch.getStatusCode(), ch.getStatusString(),
  426. *failureArgs)
  427. def checkHttp(self):
  428. # Creates an HTTPClient, if possible, if we don't have one
  429. # already. This might fail if the OpenSSL library isn't
  430. # available. Returns the HTTPClient (also self.http), or None
  431. # if not set.
  432. if self.http == None:
  433. try:
  434. self.http = HTTPClient()
  435. except:
  436. pass
  437. return self.http
  438. def startReaderPollTask(self):
  439. print '########## startReaderPollTask'
  440. # Stop any tasks we are running now
  441. self.stopReaderPollTask()
  442. self.accept(CConnectionRepository.getOverflowEventName(),
  443. self.handleReaderOverflow)
  444. taskMgr.add(self.readerPollUntilEmpty, self.uniqueName("readerPollTask"),
  445. priority = self.taskPriority)
  446. def stopReaderPollTask(self):
  447. print '########## stopReaderPollTask'
  448. taskMgr.remove(self.uniqueName("readerPollTask"))
  449. self.ignore(CConnectionRepository.getOverflowEventName())
  450. def readerPollUntilEmpty(self, task):
  451. while self.readerPollOnce():
  452. pass
  453. return Task.cont
  454. def readerPollOnce(self):
  455. if self.checkDatagram():
  456. self.getDatagramIterator(self.private__di)
  457. self.handleDatagram(self.private__di)
  458. return 1
  459. # Unable to receive a datagram: did we lose the connection?
  460. if not self.isConnected():
  461. self.stopReaderPollTask()
  462. self.lostConnection()
  463. return 0
  464. def handleReaderOverflow(self):
  465. # this is called if the incoming-datagram queue overflowed and
  466. # we lost some data. Override and handle if desired.
  467. pass
  468. def lostConnection(self):
  469. # This should be overrided by a derived class to handle an
  470. # unexpectedly lost connection to the gameserver.
  471. self.notify.warning("Lost connection to gameserver.")
  472. def handleDatagram(self, di):
  473. # This class is meant to be pure virtual, and any classes that
  474. # inherit from it need to make their own handleDatagram method
  475. pass
  476. def send(self, datagram):
  477. # Zero-length datagrams might freak out the server. No point
  478. # in sending them, anyway.
  479. if datagram.getLength() > 0:
  480. if ConnectionRepository.notify.getDebug():
  481. print "ConnectionRepository sending datagram:"
  482. datagram.dumpHex(ostream)
  483. self.sendDatagram(datagram)
  484. # debugging funcs for simulating a network-plug-pull
  485. def pullNetworkPlug(self):
  486. self.notify.warning('*** SIMULATING A NETWORK-PLUG-PULL ***')
  487. self.setSimulatedDisconnect(1)
  488. def networkPlugPulled(self):
  489. return self.getSimulatedDisconnect()
  490. def restoreNetworkPlug(self):
  491. if self.networkPlugPulled():
  492. self.notify.info('*** RESTORING SIMULATED PULLED-NETWORK-PLUG ***')
  493. self.setSimulatedDisconnect(0)