ServerRepository.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. """ServerRepository module: contains the ServerRepository class"""
  2. from pandac.PandaModules import *
  3. from direct.distributed.MsgTypesCMU import *
  4. from direct.task import Task
  5. from direct.directnotify import DirectNotifyGlobal
  6. from direct.distributed.PyDatagram import PyDatagram
  7. from direct.distributed.PyDatagramIterator import PyDatagramIterator
  8. import time
  9. import types
  10. class ServerRepository:
  11. """ This maintains the server-side connection with a Panda server.
  12. It is only for use with the Panda LAN server provided by CMU."""
  13. notify = DirectNotifyGlobal.directNotify.newCategory("ServerRepository")
  14. class Client:
  15. """ This internal class keeps track of the data associated
  16. with each connected client. """
  17. def __init__(self, connection, netAddress, doIdBase):
  18. # The connection used to communicate with the client.
  19. self.connection = connection
  20. # The net address to the client, including IP address.
  21. # Used for reporting purposes only.
  22. self.netAddress = netAddress
  23. # The first doId in the range assigned to the client.
  24. # This also serves as a unique numeric ID for this client.
  25. # (It is sometimes called "avatarId" in some update
  26. # messages, even though the client is not required to use
  27. # this particular number as an avatar ID.)
  28. self.doIdBase = doIdBase
  29. # The set of zoneIds that the client explicitly has
  30. # interest in. The client will receive updates for all
  31. # distributed objects appearing in one of these zones.
  32. # (The client will also receive updates for all zones in
  33. # which any one of the distributed obejcts that it has
  34. # created still exist.)
  35. self.explicitInterestZoneIds = set()
  36. # The set of interest zones sent to the client at the last
  37. # update. This is the actual set of zones the client is
  38. # informed of. Changing the explicitInterestZoneIds,
  39. # above, creating or deleting objects in different zones,
  40. # or moving objects between zones, might influence this
  41. # set.
  42. self.currentInterestZoneIds = set()
  43. # A dictionary of doId -> Object, for distributed objects
  44. # currently in existence that were created by the client.
  45. self.objectsByDoId = {}
  46. # A dictionary of zoneId -> set([Object]), listing the
  47. # distributed objects assigned to each zone, of the
  48. # objects created by this client.
  49. self.objectsByZoneId = {}
  50. class Object:
  51. """ This internal class keeps track of the data associated
  52. with each extent distributed object. """
  53. def __init__(self, doId, zoneId, dclass):
  54. # The object's distributed ID.
  55. self.doId = doId
  56. # The object's current zone. Each object is associated
  57. # with only one zone.
  58. self.zoneId = zoneId
  59. # The object's class type.
  60. self.dclass = dclass
  61. # Note that the server does not store any other data about
  62. # the distributed objects; in particular, it doesn't
  63. # record its current fields. That is left to the clients.
  64. def __init__(self, tcpPort, serverAddress = None,
  65. udpPort = None, dcFileNames = None,
  66. threadedNet = None):
  67. if threadedNet is None:
  68. # Default value.
  69. threadedNet = config.GetBool('threaded-net', False)
  70. # Set up networking interfaces.
  71. numThreads = 0
  72. if threadedNet:
  73. numThreads = 1
  74. self.qcm = QueuedConnectionManager()
  75. self.qcl = QueuedConnectionListener(self.qcm, numThreads)
  76. self.qcr = QueuedConnectionReader(self.qcm, numThreads)
  77. self.cw = ConnectionWriter(self.qcm, numThreads)
  78. taskMgr.setupTaskChain('flushTask')
  79. if threadedNet:
  80. taskMgr.setupTaskChain('flushTask', numThreads = 1,
  81. threadPriority = TPLow, frameSync = True)
  82. self.tcpRendezvous = self.qcm.openTCPServerRendezvous(
  83. serverAddress or '', tcpPort, 10)
  84. self.qcl.addConnection(self.tcpRendezvous)
  85. taskMgr.add(self.listenerPoll, "serverListenerPollTask")
  86. taskMgr.add(self.readerPollUntilEmpty, "serverReaderPollTask")
  87. taskMgr.add(self.clientHardDisconnectTask, "clientHardDisconnect")
  88. # A set of clients that have recently been written to and may
  89. # need to be flushed.
  90. self.needsFlush = set()
  91. collectTcpInterval = ConfigVariableDouble('collect-tcp-interval').getValue()
  92. taskMgr.doMethodLater(collectTcpInterval, self.flushTask, 'flushTask',
  93. taskChain = 'flushTask')
  94. # A dictionary of connection -> Client object, tracking all of
  95. # the clients we currently have connected.
  96. self.clientsByConnection = {}
  97. # A similar dictionary of doIdBase -> Client object, indexing
  98. # by the client's doIdBase number instead.
  99. self.clientsByDoIdBase = {}
  100. # A dictionary of zoneId -> set([Client]), listing the clients
  101. # that have an interest in each zoneId.
  102. self.zonesToClients = {}
  103. # A dictionary of zoneId -> set([Object]), listing the
  104. # distributed objects assigned to each zone, globally.
  105. self.objectsByZoneId = {}
  106. # The number of doId's to assign to each client. Must remain
  107. # constant during server lifetime.
  108. self.doIdRange = base.config.GetInt('server-doid-range', 1000000)
  109. # An allocator object that assigns the next doIdBase to each
  110. # client.
  111. self.idAllocator = UniqueIdAllocator(0, 0xffffffff / self.doIdRange)
  112. self.dcFile = DCFile()
  113. self.dcSuffix = ''
  114. self.readDCFile(dcFileNames)
  115. def flushTask(self, task):
  116. """ This task is run periodically to flush any connections
  117. that might need it. It's only necessary in cases where
  118. collect-tcp is set true (if this is false, messages are sent
  119. immediately and do not require periodic flushing). """
  120. flush = self.needsFlush
  121. self.needsFlush = set()
  122. for client in flush:
  123. client.connection.flush()
  124. return task.again
  125. def setTcpHeaderSize(self, headerSize):
  126. """Sets the header size of TCP packets. At the present, legal
  127. values for this are 0, 2, or 4; this specifies the number of
  128. bytes to use encode the datagram length at the start of each
  129. TCP datagram. Sender and receiver must independently agree on
  130. this."""
  131. self.qcr.setTcpHeaderSize(headerSize)
  132. self.cw.setTcpHeaderSize(headerSize)
  133. def getTcpHeaderSize(self):
  134. """Returns the current setting of TCP header size. See
  135. setTcpHeaderSize(). """
  136. return self.qcr.getTcpHeaderSize()
  137. def importModule(self, dcImports, moduleName, importSymbols):
  138. """ Imports the indicated moduleName and all of its symbols
  139. into the current namespace. This more-or-less reimplements
  140. the Python import command. """
  141. module = __import__(moduleName, globals(), locals(), importSymbols)
  142. if importSymbols:
  143. # "from moduleName import symbolName, symbolName, ..."
  144. # Copy just the named symbols into the dictionary.
  145. if importSymbols == ['*']:
  146. # "from moduleName import *"
  147. if hasattr(module, "__all__"):
  148. importSymbols = module.__all__
  149. else:
  150. importSymbols = module.__dict__.keys()
  151. for symbolName in importSymbols:
  152. if hasattr(module, symbolName):
  153. dcImports[symbolName] = getattr(module, symbolName)
  154. else:
  155. raise Exception('Symbol %s not defined in module %s.' % (symbolName, moduleName))
  156. else:
  157. # "import moduleName"
  158. # Copy the root module name into the dictionary.
  159. # Follow the dotted chain down to the actual module.
  160. components = moduleName.split('.')
  161. dcImports[components[0]] = module
  162. def readDCFile(self, dcFileNames = None):
  163. """
  164. Reads in the dc files listed in dcFileNames, or if
  165. dcFileNames is None, reads in all of the dc files listed in
  166. the Configrc file.
  167. """
  168. dcFile = self.dcFile
  169. dcFile.clear()
  170. self.dclassesByName = {}
  171. self.dclassesByNumber = {}
  172. self.hashVal = 0
  173. dcImports = {}
  174. if dcFileNames == None:
  175. readResult = dcFile.readAll()
  176. if not readResult:
  177. self.notify.error("Could not read dc file.")
  178. else:
  179. searchPath = getModelPath().getValue()
  180. for dcFileName in dcFileNames:
  181. pathname = Filename(dcFileName)
  182. vfs.resolveFilename(pathname, searchPath)
  183. readResult = dcFile.read(pathname)
  184. if not readResult:
  185. self.notify.error("Could not read dc file: %s" % (pathname))
  186. self.hashVal = dcFile.getHash()
  187. # Now import all of the modules required by the DC file.
  188. for n in range(dcFile.getNumImportModules()):
  189. moduleName = dcFile.getImportModule(n)
  190. # Maybe the module name is represented as "moduleName/AI".
  191. suffix = moduleName.split('/')
  192. moduleName = suffix[0]
  193. if self.dcSuffix and self.dcSuffix in suffix[1:]:
  194. moduleName += self.dcSuffix
  195. importSymbols = []
  196. for i in range(dcFile.getNumImportSymbols(n)):
  197. symbolName = dcFile.getImportSymbol(n, i)
  198. # Maybe the symbol name is represented as "symbolName/AI".
  199. suffix = symbolName.split('/')
  200. symbolName = suffix[0]
  201. if self.dcSuffix and self.dcSuffix in suffix[1:]:
  202. symbolName += self.dcSuffix
  203. importSymbols.append(symbolName)
  204. self.importModule(dcImports, moduleName, importSymbols)
  205. # Now get the class definition for the classes named in the DC
  206. # file.
  207. for i in range(dcFile.getNumClasses()):
  208. dclass = dcFile.getClass(i)
  209. number = dclass.getNumber()
  210. className = dclass.getName() + self.dcSuffix
  211. # Does the class have a definition defined in the newly
  212. # imported namespace?
  213. classDef = dcImports.get(className)
  214. # Also try it without the dcSuffix.
  215. if classDef == None:
  216. className = dclass.getName()
  217. classDef = dcImports.get(className)
  218. if classDef == None:
  219. self.notify.debug("No class definition for %s." % (className))
  220. else:
  221. if type(classDef) == types.ModuleType:
  222. if not hasattr(classDef, className):
  223. self.notify.error("Module %s does not define class %s." % (className, className))
  224. classDef = getattr(classDef, className)
  225. if type(classDef) != types.ClassType and type(classDef) != types.TypeType:
  226. self.notify.error("Symbol %s is not a class name." % (className))
  227. else:
  228. dclass.setClassDef(classDef)
  229. self.dclassesByName[className] = dclass
  230. if number >= 0:
  231. self.dclassesByNumber[number] = dclass
  232. # listens for new clients
  233. def listenerPoll(self, task):
  234. if self.qcl.newConnectionAvailable():
  235. rendezvous = PointerToConnection()
  236. netAddress = NetAddress()
  237. newConnection = PointerToConnection()
  238. retVal = self.qcl.getNewConnection(rendezvous, netAddress,
  239. newConnection)
  240. if not retVal:
  241. return task.cont
  242. # Crazy dereferencing
  243. newConnection = newConnection.p()
  244. # Add clients information to dictionary
  245. id = self.idAllocator.allocate()
  246. doIdBase = id * self.doIdRange + 1
  247. self.notify.info(
  248. "Got client %s from %s" % (doIdBase, netAddress))
  249. client = self.Client(newConnection, netAddress, doIdBase)
  250. self.clientsByConnection[client.connection] = client
  251. self.clientsByDoIdBase[client.doIdBase] = client
  252. # Now we can start listening to that new connection.
  253. self.qcr.addConnection(newConnection)
  254. self.lastConnection = newConnection
  255. self.sendDoIdRange(client)
  256. return task.cont
  257. def readerPollUntilEmpty(self, task):
  258. """ continuously polls for new messages on the server """
  259. while self.readerPollOnce():
  260. pass
  261. return task.cont
  262. def readerPollOnce(self):
  263. """ checks for available messages to the server """
  264. availGetVal = self.qcr.dataAvailable()
  265. if availGetVal:
  266. datagram = NetDatagram()
  267. readRetVal = self.qcr.getData(datagram)
  268. if readRetVal:
  269. # need to send to message processing unit
  270. self.handleDatagram(datagram)
  271. return availGetVal
  272. def handleDatagram(self, datagram):
  273. """ switching station for messages """
  274. client = self.clientsByConnection.get(datagram.getConnection())
  275. if not client:
  276. # This shouldn't be possible, though it appears to happen
  277. # sometimes?
  278. self.notify.warning(
  279. "Ignoring datagram from unknown connection %s" % (datagram.getConnection()))
  280. return
  281. if self.notify.getDebug():
  282. self.notify.debug(
  283. "ServerRepository received datagram from %s:" % (client.doIdBase))
  284. #datagram.dumpHex(ostream)
  285. dgi = DatagramIterator(datagram)
  286. type = dgi.getUint16()
  287. if type == CLIENT_DISCONNECT_CMU:
  288. self.handleClientDisconnect(client)
  289. elif type == CLIENT_SET_INTEREST_CMU:
  290. self.handleClientSetInterest(client, dgi)
  291. elif type == CLIENT_OBJECT_GENERATE_CMU:
  292. self.handleClientCreateObject(datagram, dgi)
  293. elif type == CLIENT_OBJECT_UPDATE_FIELD:
  294. self.handleClientObjectUpdateField(datagram, dgi)
  295. elif type == CLIENT_OBJECT_UPDATE_FIELD_TARGETED_CMU:
  296. self.handleClientObjectUpdateField(datagram, dgi, targeted = True)
  297. elif type == OBJECT_DELETE_CMU:
  298. self.handleClientDeleteObject(datagram, dgi.getUint32())
  299. elif type == OBJECT_SET_ZONE_CMU:
  300. self.handleClientObjectSetZone(datagram, dgi)
  301. else:
  302. self.handleMessageType(type, dgi)
  303. def handleMessageType(self, msgType, di):
  304. self.notify.warning("unrecognized message type %s" % (msgType))
  305. def handleClientCreateObject(self, datagram, dgi):
  306. """ client wants to create an object, so we store appropriate
  307. data, and then pass message along to corresponding zones """
  308. connection = datagram.getConnection()
  309. zoneId = dgi.getUint32()
  310. classId = dgi.getUint16()
  311. doId = dgi.getUint32()
  312. client = self.clientsByConnection[connection]
  313. if self.getDoIdBase(doId) != client.doIdBase:
  314. self.notify.warning(
  315. "Ignoring attempt to create invalid doId %s from client %s" % (doId, client.doIdBase))
  316. return
  317. dclass = self.dclassesByNumber[classId]
  318. object = client.objectsByDoId.get(doId)
  319. if object:
  320. # This doId is already in use; thus, this message is
  321. # really just an update.
  322. if object.dclass != dclass:
  323. self.notify.warning(
  324. "Ignoring attempt to change object %s from %s to %s by client %s" % (
  325. doId, object.dclass.getName(), dclass.getName(), client.doIdBase))
  326. return
  327. self.setObjectZone(client, object, zoneId)
  328. else:
  329. if self.notify.getDebug():
  330. self.notify.debug(
  331. "Creating object %s of type %s by client %s" % (
  332. doId, dclass.getName(), client.doIdBase))
  333. object = self.Object(doId, zoneId, dclass)
  334. client.objectsByDoId[doId] = object
  335. client.objectsByZoneId.setdefault(zoneId, set()).add(object)
  336. self.objectsByZoneId.setdefault(zoneId, set()).add(object)
  337. self.updateClientInterestZones(client)
  338. # Rebuild the new datagram that we'll send on. We shim in the
  339. # doIdBase of the owner.
  340. dg = PyDatagram()
  341. dg.addUint16(OBJECT_GENERATE_CMU)
  342. dg.addUint32(client.doIdBase)
  343. dg.addUint32(zoneId)
  344. dg.addUint16(classId)
  345. dg.addUint32(doId)
  346. dg.appendData(dgi.getRemainingBytes())
  347. self.sendToZoneExcept(zoneId, dg, [client])
  348. def handleClientObjectUpdateField(self, datagram, dgi, targeted = False):
  349. """ Received an update request from a client. """
  350. connection = datagram.getConnection()
  351. client = self.clientsByConnection[connection]
  352. if targeted:
  353. targetId = dgi.getUint32()
  354. doId = dgi.getUint32()
  355. fieldId = dgi.getUint16()
  356. doIdBase = self.getDoIdBase(doId)
  357. owner = self.clientsByDoIdBase.get(doIdBase)
  358. object = owner and owner.objectsByDoId.get(doId)
  359. if not object:
  360. self.notify.warning(
  361. "Ignoring update for unknown object %s from client %s" % (
  362. doId, client.doIdBase))
  363. return
  364. dcfield = object.dclass.getFieldByIndex(fieldId)
  365. if dcfield == None:
  366. self.notify.warning(
  367. "Ignoring update for field %s on object %s from client %s; no such field for class %s." % (
  368. fieldId, doId, client.doIdBase, object.dclass.getName()))
  369. if client != owner:
  370. # This message was not sent by the object's owner.
  371. if not dcfield.hasKeyword('clsend') and not dcfield.hasKeyword('p2p'):
  372. self.notify.warning(
  373. "Ignoring update for %s.%s on object %s from client %s: not owner" % (
  374. object.dclass.getName(), dcfield.getName(), doId, client.doIdBase))
  375. return
  376. # We reformat the message slightly to insert the sender's
  377. # doIdBase.
  378. dg = PyDatagram()
  379. dg.addUint16(OBJECT_UPDATE_FIELD_CMU)
  380. dg.addUint32(client.doIdBase)
  381. dg.addUint32(doId)
  382. dg.addUint16(fieldId)
  383. dg.appendData(dgi.getRemainingBytes())
  384. if targeted:
  385. # A targeted update: only to the indicated client.
  386. target = self.clientsByDoIdBase.get(targetId)
  387. if not target:
  388. self.notify.warning(
  389. "Ignoring targeted update to %s for %s.%s on object %s from client %s: target not known" % (
  390. targetId,
  391. dclass.getName(), dcfield.getName(), doId, client.doIdBase))
  392. return
  393. self.cw.send(dg, target.connection)
  394. self.needsFlush.add(target)
  395. elif dcfield.hasKeyword('p2p'):
  396. # p2p: to object owner only
  397. self.cw.send(dg, owner.connection)
  398. self.needsFlush.add(owner)
  399. elif dcfield.hasKeyword('broadcast'):
  400. # Broadcast: to everyone except orig sender
  401. self.sendToZoneExcept(object.zoneId, dg, [client])
  402. elif dcfield.hasKeyword('reflect'):
  403. # Reflect: broadcast to everyone including orig sender
  404. self.sendToZoneExcept(object.zoneId, dg, [])
  405. else:
  406. self.notify.warning(
  407. "Message is not broadcast or p2p")
  408. def getDoIdBase(self, doId):
  409. """ Given a doId, return the corresponding doIdBase. This
  410. will be the owner of the object (clients may only create
  411. object doId's within their assigned range). """
  412. return int(doId / self.doIdRange) * self.doIdRange + 1
  413. def handleClientDeleteObject(self, datagram, doId):
  414. """ client deletes an object, let everyone who has interest in
  415. the object's zone know about it. """
  416. connection = datagram.getConnection()
  417. client = self.clientsByConnection[connection]
  418. object = client.objectsByDoId.get(doId)
  419. if not object:
  420. self.notify.warning(
  421. "Ignoring update for unknown object %s from client %s" % (
  422. doId, client.doIdBase))
  423. return
  424. self.sendToZoneExcept(object.zoneId, datagram, [])
  425. self.objectsByZoneId[object.zoneId].remove(object)
  426. if not self.objectsByZoneId[object.zoneId]:
  427. del self.objectsByZoneId[object.zoneId]
  428. client.objectsByZoneId[object.zoneId].remove(object)
  429. if not client.objectsByZoneId[object.zoneId]:
  430. del client.objectsByZoneId[object.zoneId]
  431. del client.objectsByDoId[doId]
  432. self.updateClientInterestZones(client)
  433. def handleClientObjectSetZone(self, datagram, dgi):
  434. """ The client is telling us the object is changing to a new
  435. zone. """
  436. doId = dgi.getUint32()
  437. zoneId = dgi.getUint32()
  438. connection = datagram.getConnection()
  439. client = self.clientsByConnection[connection]
  440. object = client.objectsByDoId.get(doId)
  441. if not object:
  442. # Don't know this object.
  443. self.notify.warning("Ignoring object location for %s: unknown" % (doId))
  444. return
  445. self.setObjectZone(client, object, zoneId)
  446. def setObjectZone(self, owner, object, zoneId):
  447. if object.zoneId == zoneId:
  448. # No change.
  449. return
  450. oldZoneId = object.zoneId
  451. self.objectsByZoneId[object.zoneId].remove(object)
  452. if not self.objectsByZoneId[object.zoneId]:
  453. del self.objectsByZoneId[object.zoneId]
  454. owner.objectsByZoneId[object.zoneId].remove(object)
  455. if not owner.objectsByZoneId[object.zoneId]:
  456. del owner.objectsByZoneId[object.zoneId]
  457. object.zoneId = zoneId
  458. self.objectsByZoneId.setdefault(zoneId, set()).add(object)
  459. owner.objectsByZoneId.setdefault(zoneId, set()).add(object)
  460. self.updateClientInterestZones(owner)
  461. # Any clients that are listening to oldZoneId but not zoneId
  462. # should receive a disable message: this object has just gone
  463. # out of scope for you.
  464. datagram = PyDatagram()
  465. datagram.addUint16(OBJECT_DISABLE_CMU)
  466. datagram.addUint32(object.doId)
  467. for client in self.zonesToClients[oldZoneId]:
  468. if client != owner:
  469. if zoneId not in client.currentInterestZoneIds:
  470. self.cw.send(datagram, client.connection)
  471. self.needsFlush.add(client)
  472. # The client is now responsible for sending a generate for the
  473. # object that just switched zones, to inform the clients that
  474. # are listening to the new zoneId but not the old zoneId.
  475. def sendDoIdRange(self, client):
  476. """ sends the client the range of doid's that the client can
  477. use """
  478. datagram = NetDatagram()
  479. datagram.addUint16(SET_DOID_RANGE_CMU)
  480. datagram.addUint32(client.doIdBase)
  481. datagram.addUint32(self.doIdRange)
  482. self.cw.send(datagram, client.connection)
  483. self.needsFlush.add(client)
  484. # a client disconnected from us, we need to update our data, also
  485. # tell other clients to remove the disconnected clients objects
  486. def handleClientDisconnect(self, client):
  487. for zoneId in client.currentInterestZoneIds:
  488. if len(self.zonesToClients[zoneId]) == 1:
  489. del self.zonesToClients[zoneId]
  490. else:
  491. self.zonesToClients[zoneId].remove(client)
  492. for object in client.objectsByDoId.values():
  493. #create and send delete message
  494. datagram = NetDatagram()
  495. datagram.addUint16(OBJECT_DELETE_CMU)
  496. datagram.addUint32(object.doId)
  497. self.sendToZoneExcept(object.zoneId, datagram, [])
  498. self.objectsByZoneId[object.zoneId].remove(object)
  499. if not self.objectsByZoneId[object.zoneId]:
  500. del self.objectsByZoneId[object.zoneId]
  501. client.objectsByDoId = {}
  502. client.objectsByZoneId = {}
  503. del self.clientsByConnection[client.connection]
  504. del self.clientsByDoIdBase[client.doIdBase]
  505. id = client.doIdBase / self.doIdRange
  506. self.idAllocator.free(id)
  507. self.qcr.removeConnection(client.connection)
  508. self.qcm.closeConnection(client.connection)
  509. def handleClientSetInterest(self, client, dgi):
  510. """ The client is specifying a particular set of zones it is
  511. interested in. """
  512. zoneIds = set()
  513. while dgi.getRemainingSize() > 0:
  514. zoneId = dgi.getUint32()
  515. zoneIds.add(zoneId)
  516. client.explicitInterestZoneIds = zoneIds
  517. self.updateClientInterestZones(client)
  518. def updateClientInterestZones(self, client):
  519. """ Something about the client has caused its set of interest
  520. zones to potentially change. Recompute them. """
  521. origZoneIds = client.currentInterestZoneIds
  522. newZoneIds = client.explicitInterestZoneIds | set(client.objectsByZoneId.keys())
  523. if origZoneIds == newZoneIds:
  524. # No change.
  525. return
  526. client.currentInterestZoneIds = newZoneIds
  527. addedZoneIds = newZoneIds - origZoneIds
  528. removedZoneIds = origZoneIds - newZoneIds
  529. for zoneId in addedZoneIds:
  530. self.zonesToClients.setdefault(zoneId, set()).add(client)
  531. # The client is opening interest in this zone. Need to get
  532. # all of the data from clients who may have objects in
  533. # this zone
  534. datagram = NetDatagram()
  535. datagram.addUint16(REQUEST_GENERATES_CMU)
  536. datagram.addUint32(zoneId)
  537. self.sendToZoneExcept(zoneId, datagram, [client])
  538. datagram = PyDatagram()
  539. datagram.addUint16(OBJECT_DISABLE_CMU)
  540. for zoneId in removedZoneIds:
  541. self.zonesToClients[zoneId].remove(client)
  542. # The client is abandoning interest in this zone. Any
  543. # objects in this zone should be disabled for the client.
  544. for object in self.objectsByZoneId.get(zoneId, []):
  545. datagram.addUint32(object.doId)
  546. self.cw.send(datagram, client.connection)
  547. self.needsFlush.add(client)
  548. def clientHardDisconnectTask(self, task):
  549. """ client did not tell us he was leaving but we lost connection to
  550. him, so we need to update our data and tell others """
  551. for client in self.clientsByConnection.values():
  552. if not self.qcr.isConnectionOk(client.connection):
  553. self.handleClientDisconnect(client)
  554. return task.cont
  555. def sendToZoneExcept(self, zoneId, datagram, exceptionList):
  556. """sends a message to everyone who has interest in the
  557. indicated zone, except for the clients on exceptionList."""
  558. if self.notify.getDebug():
  559. self.notify.debug(
  560. "ServerRepository sending to all in zone %s except %s:" % (zoneId, [c.doIdBase for c in exceptionList]))
  561. #datagram.dumpHex(ostream)
  562. for client in self.zonesToClients.get(zoneId, []):
  563. if client not in exceptionList:
  564. if self.notify.getDebug():
  565. self.notify.debug(
  566. " -> %s" % (client.doIdBase))
  567. self.cw.send(datagram, client.connection)
  568. self.needsFlush.add(client)
  569. def sendToAllExcept(self, datagram, exceptionList):
  570. """ sends a message to all connected clients, except for
  571. clients on exceptionList. """
  572. if self.notify.getDebug():
  573. self.notify.debug(
  574. "ServerRepository sending to all except %s:" % ([c.doIdBase for c in exceptionList],))
  575. #datagram.dumpHex(ostream)
  576. for client in self.clientsByConnection.values():
  577. if client not in exceptionList:
  578. if self.notify.getDebug():
  579. self.notify.debug(
  580. " -> %s" % (client.doIdBase))
  581. self.cw.send(datagram, client.connection)
  582. self.needsFlush.add(client)