ServerRepository.py 28 KB

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