ConnectionRepository.py 26 KB

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