ConnectionRepository.py 24 KB

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