ConnectionRepository.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. from PandaModules import *
  2. import Task
  3. import DirectNotifyGlobal
  4. import DirectObject
  5. class ConnectionRepository(DirectObject.DirectObject):
  6. """
  7. This is a base class for things that know how to establish a
  8. connection (and exchange datagrams) with a gameserver. This
  9. includes ClientRepository and AIRepository.
  10. """
  11. notify = DirectNotifyGlobal.directNotify.newCategory("ConnectionRepository")
  12. taskPriority = -30
  13. def __init__(self, config):
  14. DirectObject.DirectObject.__init__(self)
  15. self.config = config
  16. # Set this to 'http' to establish a connection to the server
  17. # using the HTTPClient interface, which ultimately uses the
  18. # OpenSSL socket library (even though SSL is not involved).
  19. # This is not as robust a socket library as NSPR's, but the
  20. # HTTPClient interface does a good job of negotiating the
  21. # connection over an HTTP proxy if one is in use.
  22. # Set it to 'nspr' to use Panda's net interface
  23. # (e.g. QueuedConnectionManager, etc.) to establish the
  24. # connection, which ultimately uses the NSPR socket library.
  25. # This is a much better socket library, but it may be more
  26. # than you need for most applications; and there is no support
  27. # for proxies.
  28. # Set it to 'default' to use the HTTPClient interface if a
  29. # proxy is in place, but the NSPR interface if we don't have a
  30. # proxy.
  31. self.connectMethod = self.config.GetString('connect-method', 'default')
  32. self.connectHttp = None
  33. self.http = None
  34. self.qcm = None
  35. self.cw = None
  36. self.tcpConn = None
  37. # Reader statistics
  38. self.rsDatagramCount = 0
  39. self.rsUpdateObjs = {}
  40. self.rsLastUpdate = 0
  41. self.rsDoReport = self.config.GetBool('reader-statistics', 0)
  42. self.rsUpdateInterval = self.config.GetDouble('reader-statistics-interval', 10)
  43. def connect(self, serverList,
  44. successCallback = None, successArgs = [],
  45. failureCallback = None, failureArgs = []):
  46. """
  47. Attempts to establish a connection to the server. May return
  48. before the connection is established. The two callbacks
  49. represent the two functions to call (and their arguments) on
  50. success or failure, respectively. The failure callback also
  51. gets one additional parameter, which will be passed in first:
  52. the return status code giving reason for failure, if it is
  53. known.
  54. """
  55. hasProxy = 0
  56. if self.checkHttp():
  57. proxies = self.http.getProxiesForUrl(serverList[0])
  58. hasProxy = (proxies != 'DIRECT')
  59. if hasProxy:
  60. self.notify.info("Connecting to gameserver via proxy list: %s" % (proxies))
  61. else:
  62. self.notify.info("Connecting to gameserver directly (no proxy).");
  63. if self.connectMethod == 'http':
  64. self.connectHttp = 1
  65. elif self.connectMethod == 'nspr':
  66. self.connectHttp = 0
  67. else:
  68. self.connectHttp = (hasProxy or serverList[0].isSsl())
  69. self.bootedIndex = None
  70. self.bootedText = None
  71. if self.connectHttp:
  72. # In the HTTP case, we can't just iterate through the list
  73. # of servers, because each server attempt requires
  74. # spawning a request and then coming back later to check
  75. # the success or failure. Instead, we start the ball
  76. # rolling by calling the connect callback, which will call
  77. # itself repeatedly until we establish a connection (or
  78. # run out of servers).
  79. ch = self.http.makeChannel(0)
  80. self.httpConnectCallback(ch, serverList, 0,
  81. successCallback, successArgs,
  82. failureCallback, failureArgs)
  83. else:
  84. if self.qcm == None:
  85. self.qcm = QueuedConnectionManager()
  86. if self.cw == None:
  87. self.cw = ConnectionWriter(self.qcm, 0)
  88. self.qcr = QueuedConnectionReader(self.qcm, 0)
  89. minLag = self.config.GetFloat('min-lag', 0.)
  90. maxLag = self.config.GetFloat('max-lag', 0.)
  91. if minLag or maxLag:
  92. self.qcr.startDelay(minLag, maxLag)
  93. # A big old 20 second timeout.
  94. gameServerTimeoutMs = self.config.GetInt("game-server-timeout-ms",
  95. 20000)
  96. # Try each of the servers in turn.
  97. for url in serverList:
  98. self.notify.info("Connecting to %s via NSPR interface." % (url.cStr()))
  99. self.tcpConn = self.qcm.openTCPClientConnection(
  100. url.getServer(), url.getPort(),
  101. gameServerTimeoutMs)
  102. if self.tcpConn:
  103. self.tcpConn.setNoDelay(1)
  104. self.qcr.addConnection(self.tcpConn)
  105. self.startReaderPollTask()
  106. if successCallback:
  107. successCallback(*successArgs)
  108. return
  109. # Failed to connect.
  110. if failureCallback:
  111. failureCallback(0, *failureArgs)
  112. def disconnect(self):
  113. """Closes the previously-established connection.
  114. """
  115. self.notify.info("Closing connection to server.")
  116. if self.tcpConn != None:
  117. if self.connectHttp:
  118. self.tcpConn.close()
  119. else:
  120. self.qcm.closeConnection(self.tcpConn)
  121. self.tcpConn = None
  122. self.stopReaderPollTask()
  123. def httpConnectCallback(self, ch, serverList, serverIndex,
  124. successCallback, successArgs,
  125. failureCallback, failureArgs):
  126. if ch.isConnectionReady():
  127. self.tcpConn = ch.getConnection()
  128. self.tcpConn.userManagesMemory = 1
  129. self.startReaderPollTask()
  130. if successCallback:
  131. successCallback(*successArgs)
  132. elif serverIndex < len(serverList):
  133. # No connection yet, but keep trying.
  134. url = serverList[serverIndex]
  135. self.notify.info("Connecting to %s via HTTP interface." % (url.cStr()))
  136. ch.beginConnectTo(DocumentSpec(url))
  137. ch.spawnTask(name = 'connect-to-server',
  138. callback = self.httpConnectCallback,
  139. extraArgs = [ch, serverList, serverIndex + 1,
  140. successCallback, successArgs,
  141. failureCallback, failureArgs])
  142. else:
  143. # No more servers to try; we have to give up now.
  144. if failureCallback:
  145. failureCallback(ch.getStatusCode(), *failureArgs)
  146. def checkHttp(self):
  147. # Creates an HTTPClient, if possible, if we don't have one
  148. # already. This might fail if the OpenSSL library isn't
  149. # available. Returns the HTTPClient (also self.http), or None
  150. # if not set.
  151. if self.http == None:
  152. try:
  153. self.http = HTTPClient()
  154. except:
  155. pass
  156. return self.http
  157. def startReaderPollTask(self):
  158. # Stop any tasks we are running now
  159. self.stopReaderPollTask()
  160. taskMgr.add(self.readerPollUntilEmpty, "readerPollTask",
  161. priority = self.taskPriority)
  162. def stopReaderPollTask(self):
  163. taskMgr.remove("readerPollTask")
  164. def readerPollUntilEmpty(self, task):
  165. while self.readerPollOnce():
  166. pass
  167. return Task.cont
  168. def readerPollOnce(self):
  169. # we simulate the network plug being pulled by setting tcpConn
  170. # to None; enforce that condition
  171. if not self.tcpConn:
  172. return 0
  173. # Make sure any recently-sent datagrams are flushed when the
  174. # time expires, if we're in collect-tcp mode.
  175. self.tcpConn.considerFlush()
  176. if self.rsDoReport:
  177. self.reportReaderStatistics()
  178. if self.connectHttp:
  179. datagram = Datagram()
  180. if self.tcpConn.receiveDatagram(datagram):
  181. if self.rsDoReport:
  182. self.rsDatagramCount += 1
  183. self.handleDatagram(datagram)
  184. return 1
  185. # Unable to receive a datagram: did we lose the connection?
  186. if self.tcpConn.isClosed():
  187. self.tcpConn = None
  188. self.stopReaderPollTask()
  189. self.lostConnection()
  190. return 0
  191. else:
  192. self.ensureValidConnection()
  193. if self.qcr.dataAvailable():
  194. datagram = NetDatagram()
  195. if self.qcr.getData(datagram):
  196. if self.rsDoReport:
  197. self.rsDatagramCount += 1
  198. self.handleDatagram(datagram)
  199. return 1
  200. return 0
  201. def flush(self):
  202. # Ensure the latest has been sent to the server.
  203. if self.tcpConn:
  204. self.tcpConn.flush()
  205. def ensureValidConnection(self):
  206. # Was the connection reset?
  207. if self.connectHttp:
  208. pass
  209. else:
  210. if self.qcm.resetConnectionAvailable():
  211. resetConnectionPointer = PointerToConnection()
  212. if self.qcm.getResetConnection(resetConnectionPointer):
  213. resetConn = resetConnectionPointer.p()
  214. self.qcm.closeConnection(resetConn)
  215. # if we've simulated a network plug pull, restore the
  216. # simulated plug
  217. self.restoreNetworkPlug()
  218. if self.tcpConn.this == resetConn.this:
  219. self.tcpConn = None
  220. self.stopReaderPollTask()
  221. self.lostConnection()
  222. else:
  223. self.notify.warning("Lost unknown connection.")
  224. def lostConnection(self):
  225. # This should be overrided by a derived class to handle an
  226. # unexpectedly lost connection to the gameserver.
  227. self.notify.warning("Lost connection to gameserver.")
  228. def handleDatagram(self, datagram):
  229. # This class is meant to be pure virtual, and any classes that
  230. # inherit from it need to make their own handleDatagram method
  231. pass
  232. def reportReaderStatistics(self):
  233. now = globalClock.getRealTime()
  234. if now - self.rsLastUpdate < self.rsUpdateInterval:
  235. return
  236. self.rsLastUpdate = now
  237. self.notify.info("Received %s datagrams" % (self.rsDatagramCount))
  238. if self.rsUpdateObjs:
  239. self.notify.info("Updates: %s" % (self.rsUpdateObjs))
  240. self.rsDatagramCount = 0
  241. self.rsUpdateObjs = {}
  242. def send(self, datagram):
  243. #if self.notify.getDebug():
  244. # print "ConnectionRepository sending datagram:"
  245. # datagram.dumpHex(ostream)
  246. if not self.tcpConn:
  247. self.notify.warning("Unable to send message after connection is closed.")
  248. return
  249. if self.connectHttp:
  250. if not self.tcpConn.sendDatagram(datagram):
  251. self.notify.warning("Could not send datagram.")
  252. else:
  253. self.cw.send(datagram, self.tcpConn)
  254. # debugging funcs for simulating a network-plug-pull
  255. def pullNetworkPlug(self):
  256. self.restoreNetworkPlug()
  257. self.notify.warning('*** SIMULATING A NETWORK-PLUG-PULL ***')
  258. self.hijackedTcpConn = self.tcpConn
  259. self.tcpConn = None
  260. def networkPlugPulled(self):
  261. return hasattr(self, 'hijackedTcpConn')
  262. def restoreNetworkPlug(self):
  263. if self.networkPlugPulled():
  264. self.notify.info('*** RESTORING SIMULATED PULLED-NETWORK-PLUG ***')
  265. self.tcpConn = self.hijackedTcpConn
  266. del self.hijackedTcpConn
  267. def doFind(self, str):
  268. """ returns list of distributed objects with matching str in value """
  269. for value in self.doId2do.values():
  270. if `value`.find(str) >= 0:
  271. return value
  272. def doFindAll(self, str):
  273. """ returns list of distributed objects with matching str in value """
  274. matches = []
  275. for value in self.doId2do.values():
  276. if `value`.find(str) >= 0:
  277. matches.append(value)
  278. return matches