ConnectionRepository.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. from pandac.PandaModules import *
  2. from direct.task import Task
  3. from direct.directnotify import DirectNotifyGlobal
  4. from direct.showbase import DirectObject
  5. from PyDatagram import PyDatagram
  6. from PyDatagramIterator import PyDatagramIterator
  7. import types
  8. import imp
  9. class ConnectionRepository(DirectObject.DirectObject, CConnectionRepository):
  10. """
  11. This is a base class for things that know how to establish a
  12. connection (and exchange datagrams) with a gameserver. This
  13. includes ClientRepository and AIRepository.
  14. """
  15. notify = DirectNotifyGlobal.directNotify.newCategory("ConnectionRepository")
  16. taskPriority = -30
  17. def __init__(self, config):
  18. DirectObject.DirectObject.__init__(self)
  19. CConnectionRepository.__init__(self)
  20. self.setPythonRepository(self)
  21. self.config = config
  22. # Set this to 'http' to establish a connection to the server
  23. # using the HTTPClient interface, which ultimately uses the
  24. # OpenSSL socket library (even though SSL is not involved).
  25. # This is not as robust a socket library as NSPR's, but the
  26. # HTTPClient interface does a good job of negotiating the
  27. # connection over an HTTP proxy if one is in use.
  28. # Set it to 'nspr' to use Panda's net interface
  29. # (e.g. QueuedConnectionManager, etc.) to establish the
  30. # connection, which ultimately uses the NSPR socket library.
  31. # This is a much better socket library, but it may be more
  32. # than you need for most applications; and there is no support
  33. # for proxies.
  34. # Set it to 'default' to use the HTTPClient interface if a
  35. # proxy is in place, but the NSPR interface if we don't have a
  36. # proxy.
  37. self.connectMethod = self.config.GetString('connect-method', 'default')
  38. self.connectHttp = None
  39. self.http = None
  40. # This DatagramIterator is constructed once, and then re-used
  41. # each time we read a datagram.
  42. self.__di = PyDatagramIterator()
  43. self.recorder = None
  44. # This is the string that is appended to symbols read from the
  45. # DC file. The AIRepository will redefine this to 'AI'.
  46. self.dcSuffix = ''
  47. def readDCFile(self, dcFileNames = None):
  48. """ Reads in the dc files listed in dcFileNames, or if
  49. dcFileNames is None, reads in all of the dc files listed in
  50. the Configrc file. """
  51. dcFile = self.getDcFile()
  52. dcFile.clear()
  53. self.dclassesByName = {}
  54. self.dclassesByNumber = {}
  55. self.hashVal = 0
  56. dcImports = {}
  57. if dcFileNames == None:
  58. readResult = dcFile.readAll()
  59. if not readResult:
  60. self.notify.error("Could not read dc file.")
  61. else:
  62. for dcFileName in dcFileNames:
  63. readResult = dcFile.read(Filename(dcFileName))
  64. if not readResult:
  65. self.notify.error("Could not read dc file: %s" % (dcFileName))
  66. self.hashVal = dcFile.getHash()
  67. # Now import all of the modules required by the DC file.
  68. for n in range(dcFile.getNumImportModules()):
  69. moduleName = dcFile.getImportModule(n)
  70. # Maybe the module name is represented as "moduleName/AI".
  71. suffix = moduleName.split('/')
  72. moduleName = suffix[0]
  73. if self.dcSuffix and self.dcSuffix in suffix[1:]:
  74. moduleName += self.dcSuffix
  75. importSymbols = []
  76. for i in range(dcFile.getNumImportSymbols(n)):
  77. symbolName = dcFile.getImportSymbol(n, i)
  78. # Maybe the symbol name is represented as "symbolName/AI".
  79. suffix = symbolName.split('/')
  80. symbolName = suffix[0]
  81. if self.dcSuffix and self.dcSuffix in suffix[1:]:
  82. symbolName += self.dcSuffix
  83. importSymbols.append(symbolName)
  84. self.importModule(dcImports, moduleName, importSymbols)
  85. # Now get the class definition for the classes named in the DC
  86. # file.
  87. for i in range(dcFile.getNumClasses()):
  88. dclass = dcFile.getClass(i)
  89. number = dclass.getNumber()
  90. className = dclass.getName() + self.dcSuffix
  91. # Does the class have a definition defined in the newly
  92. # imported namespace?
  93. classDef = dcImports.get(className)
  94. if classDef == None:
  95. self.notify.info("No class definition for %s." % (className))
  96. else:
  97. if type(classDef) == types.ModuleType:
  98. if not hasattr(classDef, className):
  99. self.notify.error("Module %s does not define class %s." % (className, className))
  100. classDef = getattr(classDef, className)
  101. if type(classDef) != types.ClassType:
  102. self.notify.error("Symbol %s is not a class name." % (className))
  103. else:
  104. dclass.setClassDef(classDef)
  105. self.dclassesByName[className] = dclass
  106. self.dclassesByNumber[number] = dclass
  107. def importModule(self, dcImports, moduleName, importSymbols):
  108. """ Imports the indicated moduleName and all of its symbols
  109. into the current namespace. This more-or-less reimplements
  110. the Python import command. """
  111. module = __import__(moduleName, globals(), locals(), importSymbols)
  112. if importSymbols:
  113. # "from moduleName import symbolName, symbolName, ..."
  114. # Copy just the named symbols into the dictionary.
  115. if importSymbols == ['*']:
  116. # "from moduleName import *"
  117. if hasattr(module, "__all__"):
  118. importSymbols = module.__all__
  119. else:
  120. importSymbols = module.__dict__.keys()
  121. for symbolName in importSymbols:
  122. if hasattr(module, symbolName):
  123. dcImports[symbolName] = getattr(module, symbolName)
  124. else:
  125. raise StandardError, 'Symbol %s not defined in module %s.' % (symbolName, moduleName)
  126. else:
  127. # "import moduleName"
  128. # Copy the root module name into the dictionary.
  129. # Follow the dotted chain down to the actual module.
  130. components = moduleName.split('.')
  131. dcImports[components[0]] = module
  132. def connect(self, serverList,
  133. successCallback = None, successArgs = [],
  134. failureCallback = None, failureArgs = []):
  135. """
  136. Attempts to establish a connection to the server. May return
  137. before the connection is established. The two callbacks
  138. represent the two functions to call (and their arguments) on
  139. success or failure, respectively. The failure callback also
  140. gets one additional parameter, which will be passed in first:
  141. the return status code giving reason for failure, if it is
  142. known.
  143. """
  144. ## if self.recorder and self.recorder.isPlaying():
  145. ## # If we have a recorder and it's already in playback mode,
  146. ## # don't actually attempt to connect to a gameserver since
  147. ## # we don't need to. Just let it play back the data.
  148. ## self.notify.info("Not connecting to gameserver; using playback data instead.")
  149. ## self.connectHttp = 1
  150. ## self.tcpConn = SocketStreamRecorder()
  151. ## self.recorder.addRecorder('gameserver', self.tcpConn)
  152. ## self.startReaderPollTask()
  153. ## if successCallback:
  154. ## successCallback(*successArgs)
  155. ## return
  156. hasProxy = 0
  157. if self.checkHttp():
  158. proxies = self.http.getProxiesForUrl(serverList[0])
  159. hasProxy = (proxies != 'DIRECT')
  160. if hasProxy:
  161. self.notify.info("Connecting to gameserver via proxy list: %s" % (proxies))
  162. else:
  163. self.notify.info("Connecting to gameserver directly (no proxy).");
  164. if self.connectMethod == 'http':
  165. self.connectHttp = 1
  166. elif self.connectMethod == 'nspr':
  167. self.connectHttp = 0
  168. else:
  169. self.connectHttp = (hasProxy or serverList[0].isSsl())
  170. self.bootedIndex = None
  171. self.bootedText = None
  172. if self.connectHttp:
  173. # In the HTTP case, we can't just iterate through the list
  174. # of servers, because each server attempt requires
  175. # spawning a request and then coming back later to check
  176. # the success or failure. Instead, we start the ball
  177. # rolling by calling the connect callback, which will call
  178. # itself repeatedly until we establish a connection (or
  179. # run out of servers).
  180. ch = self.http.makeChannel(0)
  181. self.httpConnectCallback(ch, serverList, 0,
  182. successCallback, successArgs,
  183. failureCallback, failureArgs)
  184. else:
  185. # Try each of the servers in turn.
  186. for url in serverList:
  187. self.notify.info("Connecting to %s via NSPR interface." % (url.cStr()))
  188. if self.tryConnectNspr(url):
  189. self.startReaderPollTask()
  190. if successCallback:
  191. successCallback(*successArgs)
  192. return
  193. # Failed to connect.
  194. if failureCallback:
  195. failureCallback(0, '', *failureArgs)
  196. def disconnect(self):
  197. """Closes the previously-established connection.
  198. """
  199. self.notify.info("Closing connection to server.")
  200. CConnectionRepository.disconnect(self)
  201. self.stopReaderPollTask()
  202. def httpConnectCallback(self, ch, serverList, serverIndex,
  203. successCallback, successArgs,
  204. failureCallback, failureArgs):
  205. if ch.isConnectionReady():
  206. self.setConnectionHttp(ch)
  207. ## if self.recorder:
  208. ## # If we have a recorder, we wrap the connect inside a
  209. ## # SocketStreamRecorder, which will trap incoming data
  210. ## # when the recorder is set to record mode. (It will
  211. ## # also play back data when the recorder is in playback
  212. ## # mode, but in that case we never get this far in the
  213. ## # code, since we just create an empty
  214. ## # SocketStreamRecorder without actually connecting to
  215. ## # the gameserver.)
  216. ## stream = SocketStreamRecorder(self.tcpConn, 1)
  217. ## self.recorder.addRecorder('gameserver', stream)
  218. ## # In this case, we pass ownership of the original
  219. ## # connection to the SocketStreamRecorder object.
  220. ## self.tcpConn.userManagesMemory = 0
  221. ## self.tcpConn = stream
  222. self.startReaderPollTask()
  223. if successCallback:
  224. successCallback(*successArgs)
  225. elif serverIndex < len(serverList):
  226. # No connection yet, but keep trying.
  227. url = serverList[serverIndex]
  228. self.notify.info("Connecting to %s via HTTP interface." % (url.cStr()))
  229. ch.preserveStatus()
  230. ch.beginConnectTo(DocumentSpec(url))
  231. ch.spawnTask(name = 'connect-to-server',
  232. callback = self.httpConnectCallback,
  233. extraArgs = [ch, serverList, serverIndex + 1,
  234. successCallback, successArgs,
  235. failureCallback, failureArgs])
  236. else:
  237. # No more servers to try; we have to give up now.
  238. if failureCallback:
  239. failureCallback(ch.getStatusCode(), ch.getStatusString(),
  240. *failureArgs)
  241. def checkHttp(self):
  242. # Creates an HTTPClient, if possible, if we don't have one
  243. # already. This might fail if the OpenSSL library isn't
  244. # available. Returns the HTTPClient (also self.http), or None
  245. # if not set.
  246. if self.http == None:
  247. try:
  248. self.http = HTTPClient()
  249. except:
  250. pass
  251. return self.http
  252. def startReaderPollTask(self):
  253. # Stop any tasks we are running now
  254. self.stopReaderPollTask()
  255. taskMgr.add(self.readerPollUntilEmpty, "readerPollTask",
  256. priority = self.taskPriority)
  257. def stopReaderPollTask(self):
  258. taskMgr.remove("readerPollTask")
  259. def readerPollUntilEmpty(self, task):
  260. while self.readerPollOnce():
  261. pass
  262. return Task.cont
  263. def readerPollOnce(self):
  264. if self.checkDatagram():
  265. self.getDatagramIterator(self.__di)
  266. self.handleDatagram(self.__di)
  267. return 1
  268. # Unable to receive a datagram: did we lose the connection?
  269. if not self.isConnected():
  270. self.stopReaderPollTask()
  271. self.lostConnection()
  272. return 0
  273. def lostConnection(self):
  274. # This should be overrided by a derived class to handle an
  275. # unexpectedly lost connection to the gameserver.
  276. self.notify.warning("Lost connection to gameserver.")
  277. def handleDatagram(self, di):
  278. # This class is meant to be pure virtual, and any classes that
  279. # inherit from it need to make their own handleDatagram method
  280. pass
  281. def send(self, datagram):
  282. self.sendDatagram(datagram)
  283. # debugging funcs for simulating a network-plug-pull
  284. def pullNetworkPlug(self):
  285. self.notify.warning('*** SIMULATING A NETWORK-PLUG-PULL ***')
  286. self.setSimulatedDisconnect(1)
  287. def networkPlugPulled(self):
  288. return self.getSimulatedDisconnect()
  289. def restoreNetworkPlug(self):
  290. if self.networkPlugPulled():
  291. self.notify.info('*** RESTORING SIMULATED PULLED-NETWORK-PLUG ***')
  292. self.setSimulatedDisconnect(0)
  293. def doFind(self, str):
  294. """ returns list of distributed objects with matching str in value """
  295. for value in self.doId2do.values():
  296. if `value`.find(str) >= 0:
  297. return value
  298. def doFindAll(self, str):
  299. """ returns list of distributed objects with matching str in value """
  300. matches = []
  301. for value in self.doId2do.values():
  302. if `value`.find(str) >= 0:
  303. matches.append(value)
  304. return matches